PHP

PHP is a popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.

PHP

Get first parameter value alphabetically from array of arrays

13 Jun, 2024
PHP
Using this solution we find and display the item from an array of associative arrays that has any specified attribute (like title, name, etc.) which comes first alphabetically. This approach can be...
PHP

PHP: Strip double whitespace, keeping only one space

11 Mar, 2024
PHP
In PHP, the task of stripping double whitespace while retaining only one space involves utilizing regular expressions or string manipulation functions. The regular expression /\\s+/ serves as a key...
PHP

Filter by array key, using pattern in PHP

8 Mar, 2024
PHP
To filter an array by key using a pattern in PHP, you can use functions like array_filter() and regular expressions. In this example, preg_match() is used to check if the key matches the defined...
PHP

PHP: string contains (case-insensitive)

7 Mar, 2024
PHP
To check if a string contains another string in PHP in a case-insensitive manner, you can use the stripos() function. stripos() returns the position of the first occurrence of a substring in a string...
PHP

strtotime() from timestamp in PHP

7 Feb, 2024
PHP
In PHP, the most common and straightforward method to convert datetime strings to timestamps is by using the strtotime() function. So even when this seems like a pointless exercise, you might...
PHP

PHP: Use regex to remove part of a string

4 Feb, 2024
PHP
If you want to remove certain patterns from a string in PHP using regular expressions, you can use the preg_replace function. Clone this snippet and replace "/pattern/" with the actual regular...
PHP

DateTime from timestamp in PHP

3 Feb, 2024
PHP
The PHP code snippet creates a DateTime object using a Unix timestamp. The "@" symbol before the timestamp is how DateTime is interpreting the value as a Unix timestamp rather than a regular date...
PHP

Strip URL Parameters in PHP

31 Jan, 2024
PHP
There are 2 methods you can use for this. The parse_url method involves breaking down the URL into components using PHP's built-in function, allowing for selective extraction of the scheme, host, and...
PHP

PHP Replace HTML Tags in String

31 Dec, 2023
PHP
Stripping or replacing HTML tags in a string using PHP is a common practice for various reasons. For instance, it helps enhance security by removing HTML tags from user-generated content, mitigating...
PHP

PHP: How to break function?

30 Dec, 2023
PHP
In PHP, you can use the return statement to exit a function and return a value if needed. The return statement not only returns a value but also exits the function immediately.
PHP

Add a suffix to each item of a PHP array

12 Dec, 2023
PHP
Using preg_filter to add a suffix ("_suffix") to each item in the array. Use this one-liner to for good performance and easy solution. There are other solutions, but this is the preferred one.
PHP

Add a prefix to each item of a PHP array

12 Dec, 2023
PHP
Utilizes preg_filter to add the specified prefix to each item in the array. There are other methods, but this is fast and a single-liner.
PHP

Decode: Content-Transfer-Encoding: 8Bit in PHP

12 Dec, 2023
PHP
"Content-Transfer-Encoding: 8Bit" is a header used in email messages to indicate the type of encoding used for the content. If you're trying to decode a message with this encoding, you'll need to...
PHP

PHP: Get last quarter start and end timestamps

14 Nov, 2023
PHP
The code snippet use the DateTime class to calculate the start and end timestamps for the previous quarter. The calculations take into account the current month and adjust it to correctly identify...
PHP

Start and end days of week based on the first day of the week

13 Nov, 2023
PHP
This PHP code snippet provides a convenient way to determine the start and end days of the current week based on a user-specified first day. By setting the `$week_start_day` variable (0 for Sunday, 1...
PHP

Convert milliseconds to time (H:i:s) in PHP

24 Oct, 2023
PHP
This snippet takes a number of milliseconds and converts it into a time format displaying hours, minutes, and seconds. The result is a formatted time string in the "H:i:s" format. This way, if you...
PHP

Convert time (H:i:s) to milliseconds in PHP

24 Oct, 2023
PHP
Convert a time in the format H:i:s (hours:minutes:seconds) to milliseconds in PHP. In this code, we first split the time string into hours, minutes, and seconds using the explode function. Then, we...
PHP

Split string with characters in PHP

30 Sep, 2023
PHP
Split string with characters in PHP. You can achieve this by taking a string $str, split it into chunks of 2 characters each with colons in between, and then remove any trailing colon from the...
PHP

Decode HTML Entities in PHP

25 Aug, 2023
PHP
HTML entities are special codes used to represent characters that have reserved meanings or are difficult to include directly in HTML code. These entities, like & for "&" or < for "<,"...
PHP

Rotate an image to its EXIF Orientation in PHP

19 Aug, 2023
PHP
While iPhones and many modern cameras save images with orientation information in their EXIF data, the correct display of these images can sometimes be an issue on other devices or in browsers. Being...
PHP

Multidimensional values as key and value pairs in PHP

6 Jul, 2023
PHP
The PHP code snippet demonstrates how to extract last names as keys and first names as values from a multidimensional array using the array_column function. The array, named $records, contains...
PHP

Converting ISO Date to Timestamp in PHP

6 Jul, 2023
PHP
Example of how to convert an ISO date to a timestamp in PHP. It introduces the strtotime() function, which is a powerful tool for parsing textual datetime descriptions. By following the step-by-step...
PHP

Convert File URI to Relative Path in Drupal 7

6 Jul, 2023
PHP
This code snippet demonstrates how to convert a file URI to a relative path in Drupal 7 using the drupal_realpath() function. By providing the file URI as input, the function returns the...
PHP

"do-while" loop in PHP

30 Apr, 2023
PHP
A "do-while" loop is a type of loop construct used in programming to execute a block of code repeatedly until a certain condition is met. The code inside the "do" block will be executed at least once...
PHP

Move a Key to the End of a PHP Array

27 Apr, 2023
PHP
When working with associative arrays in PHP, there may be times when you need to reorder the elements of the array. For example, you may want to move a specific key and its value to the end of the...
PHP

Differences using the + operator and the array_merge() function in PHP

27 Mar, 2023
PHP
In PHP, you can combine two or more arrays using the + operator or the array_merge() function. While both approaches combine arrays, there are some differences to consider.
PHP

Convert time to utc from timezone in PHP

11 Nov, 2022
PHP
Working with timezones can be tricky and if you do migration of data from/to somewhere. You might have to correct timezones. This snippet shows how you can change dates based on timezone difference.
PHP

PHP - str_replace() all variations

14 May, 2022
PHP
Collection of all variants of str_replace function like functionality. Examples providing all kinds of solutions for your needs. From simple string replacement to regular expressions.
PHP

PHP: Zendesk api attach file to ticket

19 Apr, 2022
PHP
You can't directly add a file to a ticket, but y can upload a file and attach it to a ticket comment. The attachment appears in the ticket comment. You can only attach the uploaded file to a ticket...
PHP

PHP: OneSky api get translations

21 Dec, 2021
PHP
Example where we download via api and parse translations. In multiple language export there is only one format "I18NEXT_MULTILINGUAL_JSON". That format does cut phrase ids using "." as a separator....
PHP

PHP: Imagick rotate and merge

1 Dec, 2021
PHP
Rotate and merge image using data from css transform. In this code example the input data comes from javascript where visually image is rotated using css transform property. CSS transform and Imagick...
PHP

PHP: Imagick resize / scale image

1 Dec, 2021
PHP
Change the size of an image by resize or scale an image. The resizeImage method is an inbuilt function in PHP which is used to scale an image to the desired dimensions.
PHP

PHP: Imagick transparent background

30 Nov, 2021
PHP
In order to work with transparent images, you have to define image as transparent. Do that immediately after creating an instance, by setting the object's default background color with...
PHP

PHP: Imagick read image files from URL

24 Nov, 2021
PHP
The code example shows how to read an image from url to Imagick. Imagick doesn't take in url directly, but it has a method for reading file as binary content. So we just need to get the content form...
PHP

MQL5 for GeSHi

1 Oct, 2021
PHP
MQL5 language file for GeSHi (Generic Syntax Highlighter). I used C++ langague file to base this on, since MQL is based on C++. I don't think it's the best possible highlight and ideally would use...
PHP

PHP error: class 'DateTimeZone' not found

1 Mar, 2021
PHP
DateTimeZone class is built into php. If you get error that it's missing, then it's namespace problem.
PHP

PHP connect to Azure DB

11 Feb, 2020
PHP
This snippet shows you how to connect to Azure database for you to run some scripts for an example. In this example we use ODBC class not through PDO. You need to download two packages from your...
PHP

Trim Array Whitespace in PHP

23 Oct, 2019
PHP
This snippet shows you how to trim whitespaces from each array value in PHP. Expects all array values to be strings.
PHP

Encode, decode and output JSON in PHP

11 Sep, 2019
PHP
This class provides several static functions for handling JSON data in PHP. These functions include options for encoding, decoding, and outputting JSON, and are intended to be independent of the user...
PHP

PHP: Check string for a specific word

6 Aug, 2019
PHP
The fastest string parsing is using existing functions, in this case you can use the strpos() which is used to find the occurrence of one string inside another one. When you need a stripos() for a...
PHP

PHP Output Buffering

24 Jul, 2019
PHP
Output buffering catches all echo-s, print-s and other output to stdOut. Then you can call a function on script shutdown to output all of the content. You can buffer output and stop scripts from...
PHP

Set Up Laravel, PHP 7.3, Nginx, and MySQL with Docker

11 May, 2019
PHP
Another way to setup Laravel expecting that you have git and composer installed on your machine. Presented in configuration file examples for fastest reading/setup.
PHP

Show all errors for development in PHP

26 Mar, 2019
PHP

Usually in default errors are disabled for production. Sometimes you have error 500 for an example and you need to see the error message. For an example in Drupal 7 you can put this in settings.php...
PHP

PHP: Send json with post request

26 Nov, 2018
PHP
Instead of curl I like to use http request function from a long and stable framework PHP: http request function, alternative to curl or file_get_contents. Because I find curl to be tedious. Using...
PHP

Magento 2: Module is not listing

18 Oct, 2018
PHP
When you copy a custom module to app/code directory. Magento does not pick it up automatically. You need to run this.
PHP

Number to words in PHP

24 Jul, 2018
PHP
Helper function for converting numbers to words. There is same function available in PHPs NumberFormatter class, but using it is not always possible, since it's not enabled by default.
PHP

PHP: http request function, alternative to curl or file_get_contents

12 Mar, 2018
PHP
Handles any HTTP request correctly. This is a flexible and powerful HTTP client implementation of GET, POST, PUT or any other HTTP requests. The reason I built this was due to use of url arguments...
PHP

PHP: First x characters of a string

2 Nov, 2017
PHP
Get first n amount of characters from a string. You could use substr for that, but you will get empty results when there are special characters. Thus multibyte string method is the right way to go.
PHP

PHP: Instagram to RSS feed

2 Aug, 2017
PHP
Instagram gives out json feed. You can use this little php snippet to create rss feed from the given json. The script leverages paging, which enables you to control the items count in the output feed...
PHP

PHP: Encode Url for Curl

23 May, 2017
PHP
This snippet encodes urls for curl. If you use special letters like äõöü in url, then you get a bit different url parsing from browsers than curl in PHP. You would think that you could use php's own...
PHP

PHP: Fix url query parameters starting with "&" instead of "?"

19 May, 2017
PHP
Snippet shows you how to fix url query parameters starting with "&" instead of "?". This can be useful when you have to use "parse_url" function. It cannot detect query parameters when they start...
PHP

PHP: Check url for valid response code 200

9 Jan, 2017
PHP
Check the HTTP Status Code of the website header using PHP. Check that url is giving valid response code of 2xx. You can modify this for different purposes. For detecting 404 not found only or...
PHP

Soap request with NTLM authentication

6 Dec, 2016
PHP
NTLM authentication is often used for SOAP requests, especially when connecting to Microsoft services. The PHP SoapClient does not support NTLM out of the box, so you will need to use a third-party...
PHP

PHP: Download large file from url without loading it to memory

5 Dec, 2016
PHP
This snippet shows you how to download a file from url without loading it to memory. When you use file_get_contents() and file_set_contents() you load the content to memory and then to file. The...
PHP

Filename from path in PHP

22 Nov, 2016
PHP
Snippet shows you how to get filename from a path in PHP. Filename and extension separately. Can be used for extending filenames with timestamp or anything.
PHP

Select a random file from directory in PHP

22 Nov, 2016
PHP
Select a random file from directory. This can be useful if you want to display a random image on your website. For an example a background image randomly from a directory in your files.
PHP

Get body tag using PHP Dom Document

22 Sep, 2016
PHP
To use a DOMDocument and get the contents of the body in PHP, you can use the DOMDocument class, which provides a way to parse and manipulate XML and HTML documents. Here is an example of how to use...
PHP

Validate AJAX requests in Zend 1

26 Aug, 2016
PHP
How to validate AJAX requests in Zend Framework. There is a function in request class, to use instead of comparing the $_SERVER['HTTP_X_REQUESTED_WITH'] directly. This can be beneficial for security...
PHP

Directo class

17 May, 2016
PHP
Class for fetching and sending data between http://www.directo.ee/ API. This class includes pulling data from Directo and posting xml with php array to xml generation.
PHP

PHP: Trim Array

5 May, 2016
PHP
This snippet shows you how to trim an array with single line of code. This can be achieved by using "array_map".
PHP

SimplePie Error: timed out after 10001 milliseconds

8 Feb, 2016
PHP
SimplePie is set to 10 seconds timeout in default. So if the feed has problem with speed then you can increase the time. The exact error that I got was "cURL error 28: Operation timed out after 10001...
PHP

PHP: Days since today or days between two dates

13 Jan, 2016
PHP
How to find out the amount of between two dates. For an example how many days have passed since a defined date.
PHP

Get every other member of array in PHP

11 Jan, 2016
PHP
Using a loop to check the index of the element in the array is even or odd to get every other element. Examples of getting even or odd members of an array, using foreach loop and "modulo operation"....
PHP

Enable Phar in PHP 7

10 Jan, 2016
PHP
Phar is included in PHP 7 amongst other updates. It's no longer external module. You have to turn off the "readonly" parameter. Since it disables Phar write support by default.
PHP

Cache json from curl request in PHP

5 Jan, 2016
PHP
When you create a simple request without any special REST client, you can do it just by using curl. When you need to do curl request, it's not a good practise to do it on every page load. So the...
PHP

Explode multiple delimiters PHP

4 Jan, 2016
PHP
To explode multiple delimiters PHP you have to use regular expression. Add your delimiters in the parentheses separated by pipe. You might have to escape your characters if they have meaning in PCRE...
PHP

PHP: Detect delimiter of CSV file

9 Dec, 2015
PHP
Using PHP to read csv file is a common thing to do. Sadly there is no solid standard on delimiters, depends on fully from where you get your csv file. Usually simple csv exports are a bit different...
PHP

Select next as well in PhpStorm

6 Oct, 2015
PHP
Select next, is a functionality well needed in everyday programming. For an example, if you have a function that defines a variable and the variable is used multiple times. You would like to select...
PHP

PHP: Replace all whitespaces with a single space

8 Sep, 2015
PHP
You can replace all whitespaces (space, new lines, etc.) with a single space using regular expression find and replace.
PHP

Set PhpStorm to always show line numbers

4 Sep, 2015
PHP
PhpStorm by default does not display line numbers. Working with version control or when debugging stuff, you usually get line number of the code where the error appears. So it would make sense that...
PHP

PHP: Get values by key in multidimensional array

5 Mar, 2015
PHP
How to get values by key name in multidimensional array. You have to iterate it recursively. This is the first time I can use Iterator classes of PHP and I already can think multiple problems this...
PHP

PHP: Memory management

22 Feb, 2015
PHP
If you are using larger files like bigger data files or images, memory might become an issue. Even if not, it's always good practice to use optimal amount of memory. Clearing memory is just a part of...
PHP

Php pcre regex or operator tutorial

2 Nov, 2014
PHP
PCRE regular expression operator OR. In regular expressions "or" is known as "alternatives". Create a subgroup using parenthesis.
PHP

PHP - Replace using regex

29 Oct, 2014
PHP
Search and replace using regular expression in PHP using preg_replace function. It is very powerful way to search and replace. I suggest using some online regular expression tool to test out your...
PHP

Validate UTF-8 strings in PHP

7 May, 2014
PHP
This function checks whether a string is valid UTF-8. You can ensure that the string you operate is a valid UTF-8 string. preg_match fails on strings containing invalid UTF-8 byte sequences. It does...
PHP

Convert text or HTML to plain-text in PHP

25 Nov, 2013
PHP
Encodes special characters in a plain-text string for display as HTML. Validates strings as UTF-8, if not UTF-8 it returns an empty string. It prevents CSS attacks on IE 6.
PHP

Install web server (Apache, PHP, MariaDB) on Linux Debian Wheezy

20 Nov, 2013
PHP
This tutorial shows how to prepare a Debian Wheezy web server. This is just a simple setup of basic web server. I myself did it to set up a development environment for myself.
PHP

Check if text contains cyrillic characters in PHP

5 Nov, 2013
PHP
Check if text contains cyrillic characters in PHP. This example shows you how to do exactly that.
PHP

Get words in string as array in PHP

16 Sep, 2013
PHP
How to split words in string to an array using regular expressions. You can use this for search indexing for an example.
PHP

Read or parse feeds with PHP

7 Aug, 2013
PHP
This tutorial shows how to parse RSS feeds with PHP. From the libraries and methods that I have tested and used SimplePie is by far the best PHP RSS parser. It supports most common RSS modules out of...
PHP

Convert file size in bytes to nice (human-readable) format in PHP.

6 Aug, 2013
PHP
This snippet shows you how to convert file size in bytes to nice (human-readable) format in PHP. If the size is less than 1 MB, show the size in KB, if it's between 1 MB - 1 GB show it in MB, etc.
PHP

Get img tag image url from html using regex in PHP

25 Jul, 2013
PHP
Snippet about getting img tag image url from html using regex in PHP. Example below.
PHP

Convert time to other time zone in PHP

7 May, 2013
PHP
Convert time and date from one time zone to another in PHP. Don't ever manage time adding or subtracting seconds, there is more to datetime than meets the eye.
PHP

Remove HTML elements using DOMDocument in PHP

19 Apr, 2013
PHP
This snippet shows how to remove HTML elements using DOMDocument in PHP. The problem is that you can't do it in the same loop.
PHP

Using DOMDocument to parse HTML in PHP

15 Apr, 2013
PHP
This snippet is about parsing HTML with PHP. It's hard to parse HTML, because people write incorrect HTML syntax very often. This code forces DOMDocument to read and later write HTML. So your changes...
PHP

PHP - get extension from file name

21 Mar, 2013
PHP
Get extension from file name.
PHP

Remove width and height form img tag using PHP

29 Nov, 2012
PHP
Remove width and height attributes from img tag using PHP. Really plain and simple replace width and height attributes with nothing.
PHP

PHP range where key and value is same

2 Oct, 2012
PHP
Creating range array where key and the value is the same number. I am using array_combine function for that. I give two parameters which are the same array created by range.
PHP

PHP - strip defined tags, strip_tags reverse

9 Aug, 2012
PHP
Strip tags in PHP strips all tags, except allowed tags. This function strips tags that you define. Also you can define if you want to strip content as well.
PHP

Strip tag with class, id or anything else in PHP

23 Jul, 2012
PHP
This function strips tags by any identifier without regexp, and without heavy XML parsing. As long as the tag looks exactly the same in source-code it works.
PHP

PHP Date or Time Range

12 Jul, 2012
PHP
Iterate through date or time range using PHP.
PHP

Get MSSQL Field Data Type in PHP

29 May, 2012
PHP
Example how to get field types in MSSQL. You can use it on any query, even procedures.
PHP

Detect character encoding in PHP

26 Apr, 2012
PHP
Detect character encoding in PHP and convert string to UTF-8.
PHP

Get all MSSQL tables using PHP

17 Feb, 2012
PHP
How to get all tables names that are in a certain table.
PHP

Get MySQL tables names in PHP

14 Dec, 2011
PHP
Getting MySQL tables names in PHP.
PHP

Get MySQL column types in PHP

14 Dec, 2011
PHP
How to get MySQL columns data of a table in PHP. The data includes name, type, null allowed or not, key, default value and extra for auto_increase and such.
PHP

Check if URL is external or internal in PHP

11 Oct, 2011
PHP
Check if URL is external or internal in PHP. We are going to use parse_url PHP native function. Function parse_url parses a URL and returns an associative array containing any of the various...
PHP

Get PHP script execution time

22 Aug, 2011
PHP
How to test execution time of any part of the code in PHP. Basically you have to start counting microseconds before you code execution and stop after. This snippet shows how to do the counting.
PHP

Get files content type in PHP

8 Jul, 2011
PHP
This snippet gets content type of a file form external url. This snippet uses curl to download the file and get the content type.
PHP

MySQL Query Into Array in PHP

8 May, 2011
PHP
How to turn MySQL query into an array in PHP. Print query results on screen. This is useful for determining contents of a table.
PHP

Get Years in PHP

3 May, 2011
PHP
How to get current, last and coming year in PHP. Simple examples of how you can get different years. Currently the years are calculated from the server time.
PHP

PHP: Add Zeros Before Number

20 Feb, 2011
PHP
This tutorial shows how to add or append zeros before numbers. You might need this if you want to make folders named by numbers and you want them to be in right order when browsing the folder with...
PHP

Installing Yii Framework

17 Dec, 2010
PHP
How to install and set up Yii framework application to your hosting.
PHP

Add Text to Image in PHP

15 Dec, 2010
PHP
This tutorial shows how you can add text to images with PHP. You can use it to make banners with dynamic content for an example.
PHP

How to echo or print arrays in PHP

6 Dec, 2010
PHP
Examples of parsing array values on screen. Some examples for beginners.
PHP

Storing Images in MySQL With PHP

12 Nov, 2010
PHP
Easy to understand tutorial on how to upload, store and display images in mysql database.
PHP

Create Treeview Using Recursion in PHP

9 Oct, 2010
PHP
An easy example of recursion. PHP treeview can be used to create hierarchical lists like menus including sub-menus, category trees, taxonomy trees or site maps. This tutorial shows you how to...
PHP

PHP Global Variables

15 Jul, 2010
PHP
Tutorial about global variables in PHP. How to use global, superglobal in PHP.
PHP

Handling Timestamps in PHP

25 Jun, 2010
PHP
This tutorial is about using and converting timestamps in PHP, witch are common formats of storing some timeperiod in database.
PHP

Displaying random value from array in PHP

13 Jun, 2010
PHP
This beginners tutorial shows and explains how to get random value from array in PHP.