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: Detect mime type by extension
27 Oct, 2024
If you're working in a PHP environment and want to detect MIME types by file extension, using Symfony's Mime component is a great choice. Here’s how to set it up and use it:
PHP: use docstring to mark function deprecated
15 Oct, 2024
To mark a PHP function as deprecated and provide an alternative in the docstring, use the @deprecated tag. This makes it clear to developers that the function is deprecated and specifies the...
Get first parameter value alphabetically from array of arrays
13 Jun, 2024
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: Strip double whitespace, keeping only one space
11 Mar, 2024
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...
Filter by array key, using pattern in PHP
8 Mar, 2024
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: string contains (case-insensitive)
7 Mar, 2024
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...
strtotime() from timestamp in PHP
7 Feb, 2024
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: Use regex to remove part of a string
4 Feb, 2024
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...
DateTime from timestamp in PHP
3 Feb, 2024
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...
Strip URL Parameters in PHP
31 Jan, 2024
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 Replace HTML Tags in String
31 Dec, 2023
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: How to break function?
30 Dec, 2023
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.
Add a suffix to each item of a PHP array
12 Dec, 2023
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.
Add a prefix to each item of a PHP array
12 Dec, 2023
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.
Decode: Content-Transfer-Encoding: 8Bit in PHP
12 Dec, 2023
"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: Get last quarter start and end timestamps
14 Nov, 2023
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...
Start and end days of week based on the first day of the week
13 Nov, 2023
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...
Convert milliseconds to time (H:i:s) in PHP
24 Oct, 2023
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...
Convert time (H:i:s) to milliseconds in PHP
24 Oct, 2023
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...
Split string with characters in PHP
30 Sep, 2023
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...
Decode HTML Entities in PHP
25 Aug, 2023
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 "<,"...
Rotate an image to its EXIF Orientation in PHP
19 Aug, 2023
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...
Multidimensional values as key and value pairs in PHP
6 Jul, 2023
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...
Converting ISO Date to Timestamp in PHP
6 Jul, 2023
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...
Convert File URI to Relative Path in Drupal 7
6 Jul, 2023
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...
"do-while" loop in PHP
30 Apr, 2023
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...
Move a Key to the End of a PHP Array
27 Apr, 2023
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...
Differences using the + operator and the array_merge() function in PHP
27 Mar, 2023
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.
Convert time to utc from timezone in PHP
11 Nov, 2022
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 - str_replace() all variations
14 May, 2022
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: Zendesk api attach file to ticket
19 Apr, 2022
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: OneSky api get translations
21 Dec, 2021
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: Imagick rotate and merge
1 Dec, 2021
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: Imagick resize / scale image
1 Dec, 2021
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: Imagick transparent background
30 Nov, 2021
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: Imagick read image files from URL
24 Nov, 2021
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...
MQL5 for GeSHi
1 Oct, 2021
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 error: class 'DateTimeZone' not found
1 Mar, 2021
DateTimeZone class is built into php. If you get error that it's missing, then it's namespace problem.
PHP connect to Azure DB
11 Feb, 2020
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...
Trim Array Whitespace in PHP
23 Oct, 2019
This snippet shows you how to trim whitespaces from each array value in PHP. Expects all array values to be strings.
Encode, decode and output JSON in PHP
11 Sep, 2019
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: Check string for a specific word
6 Aug, 2019
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 Output Buffering
24 Jul, 2019
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...
Set Up Laravel, PHP 7.3, Nginx, and MySQL with Docker
11 May, 2019
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.
Show all errors for development in PHP
26 Mar, 2019
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: Send json with post request
26 Nov, 2018
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...
Magento 2: Module is not listing
18 Oct, 2018
When you copy a custom module to app/code directory. Magento does not pick it up automatically. You need to run this.
Number to words in PHP
24 Jul, 2018
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: http request function, alternative to curl or file_get_contents
12 Mar, 2018
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: First x characters of a string
2 Nov, 2017
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: Instagram to RSS feed
2 Aug, 2017
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: Encode Url for Curl
23 May, 2017
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: Fix url query parameters starting with "&" instead of "?"
19 May, 2017
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: Check url for valid response code 200
9 Jan, 2017
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...
Soap request with NTLM authentication
6 Dec, 2016
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: Download large file from url without loading it to memory
5 Dec, 2016
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...
Filename from path in PHP
22 Nov, 2016
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.
Select a random file from directory in PHP
22 Nov, 2016
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.
Get body tag using PHP Dom Document
22 Sep, 2016
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...
Validate AJAX requests in Zend 1
26 Aug, 2016
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...
Directo class
17 May, 2016
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: Trim Array
5 May, 2016
This snippet shows you how to trim an array with single line of code. This can be achieved by using "array_map".
SimplePie Error: timed out after 10001 milliseconds
8 Feb, 2016
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: Days since today or days between two dates
13 Jan, 2016
How to find out the amount of between two dates. For an example how many days have passed since a defined date.
Get every other member of array in PHP
11 Jan, 2016
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"....
Enable Phar in PHP 7
10 Jan, 2016
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.
Cache json from curl request in PHP
5 Jan, 2016
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...
Explode multiple delimiters PHP
4 Jan, 2016
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: Detect delimiter of CSV file
9 Dec, 2015
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...
Select next as well in PhpStorm
6 Oct, 2015
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: Replace all whitespaces with a single space
8 Sep, 2015
You can replace all whitespaces (space, new lines, etc.) with a single space using regular expression find and replace.
Set PhpStorm to always show line numbers
4 Sep, 2015
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: Get values by key in multidimensional array
5 Mar, 2015
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: Memory management
22 Feb, 2015
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 pcre regex or operator tutorial
2 Nov, 2014
PCRE regular expression operator OR. In regular expressions "or" is known as "alternatives". Create a subgroup using parenthesis.
PHP - Replace using regex
29 Oct, 2014
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...
Validate UTF-8 strings in PHP
7 May, 2014
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...
Convert text or HTML to plain-text in PHP
25 Nov, 2013
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.
Install web server (Apache, PHP, MariaDB) on Linux Debian Wheezy
20 Nov, 2013
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.
Check if text contains cyrillic characters in PHP
5 Nov, 2013
Check if text contains cyrillic characters in PHP. This example shows you how to do exactly that.
Get words in string as array in PHP
16 Sep, 2013
How to split words in string to an array using regular expressions. You can use this for search indexing for an example.
Read or parse feeds with PHP
7 Aug, 2013
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...
Convert file size in bytes to nice (human-readable) format in PHP.
6 Aug, 2013
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.
Get img tag image url from html using regex in PHP
25 Jul, 2013
Snippet about getting img tag image url from html using regex in PHP. Example below.
Convert time to other time zone in PHP
7 May, 2013
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.
Remove HTML elements using DOMDocument in PHP
19 Apr, 2013
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.
Using DOMDocument to parse HTML in PHP
15 Apr, 2013
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...
Remove width and height form img tag using PHP
29 Nov, 2012
Remove width and height attributes from img tag using PHP. Really plain and simple replace width and height attributes with nothing.
PHP range where key and value is same
2 Oct, 2012
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 - strip defined tags, strip_tags reverse
9 Aug, 2012
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.
Strip tag with class, id or anything else in PHP
23 Jul, 2012
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.
Get MSSQL Field Data Type in PHP
29 May, 2012
Example how to get field types in MSSQL. You can use it on any query, even procedures.
Detect character encoding in PHP
26 Apr, 2012
Detect character encoding in PHP and convert string to UTF-8.
Get all MSSQL tables using PHP
17 Feb, 2012
How to get all tables names that are in a certain table.
Get MySQL column types in PHP
14 Dec, 2011
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.
Check if URL is external or internal in PHP
11 Oct, 2011
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...
Get PHP script execution time
22 Aug, 2011
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.
Get files content type in PHP
8 Jul, 2011
This snippet gets content type of a file form external url. This snippet uses curl to download the file and get the content type.
MySQL Query Into Array in PHP
8 May, 2011
How to turn MySQL query into an array in PHP. Print query results on screen. This is useful for determining contents of a table.
Get Years in PHP
3 May, 2011
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: Add Zeros Before Number
20 Feb, 2011
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...
Installing Yii Framework
17 Dec, 2010
How to install and set up Yii framework application to your hosting.
Add Text to Image in PHP
15 Dec, 2010
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.
How to echo or print arrays in PHP
6 Dec, 2010
Examples of parsing array values on screen. Some examples for beginners.
Storing Images in MySQL With PHP
12 Nov, 2010
Easy to understand tutorial on how to upload, store and display images in mysql database.
Create Treeview Using Recursion in PHP
9 Oct, 2010
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 Global Variables
15 Jul, 2010
Tutorial about global variables in PHP. How to use global, superglobal in PHP.
Handling Timestamps in PHP
25 Jun, 2010
This tutorial is about using and converting timestamps in PHP, witch are common formats of storing some timeperiod in database.
Displaying random value from array in PHP
13 Jun, 2010
This beginners tutorial shows and explains how to get random value from array in PHP.