Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP Cheatsheet


As with all cheatsheets, this is a work in progress and I'll keep adding to it.

Related Posts

Get File Handle For Output Stream

There are many useful functions in the standard library that expect a file handle to write to, but you want to output the the output stream instead. An easy solution for this is to get a handle on the output stream like so:

$fileHandle = fopen("php://output", 'w');

Then you can do something like:

$fileHandle = fopen("php://output", 'w');
$myArray = ["hello", "world"];
fputcsv($fileHandle, $myArray);

Feel free to read more on streams in case you want to do anything funky with the input stream etc.

Byte Order Mark

If you are ever generating CSV files for Excel users, you probably want to insert a byte order mark at the very start in order to tell Excel that the content is in UTF-8 format. I find it easiest to just define the byte order mark and then use it when necessary like below:

define('BYTE_ORDER_MARK', "\xEF\xBB\xBF");

Regular Expressions

This regex tutorial is particularly useful for this section.

The following can be used to mean "any kind of letter" (e.g. languages have funky characters not in a-zA-Z).


The following means any kind of whitespace character


The following means any kind of number

Below is a regular expression for a line that must be alphanumeric with spaces, underscores and hyphens with 4 or more characters (4 spaces would pass though):

/^[0-9a-zA-Z-_ ]{4,}$/

If you support foreign languages, then you may wish to use the following to allow any type of letter:

/^[\p{L}\p{N}-_ ]{4,}$/u

The /u tells PHP to enable unicode mode in PHP and this will not work on funky letters if you don't have it.

Last updated: 7th February 2019
First published: 16th August 2018