PHP Snippets

A collection of handy one-liners and useful snippets that I’ve written or collected for PHP over the years.

Remove Character Accents

Replaces accented characters in a string with their unaccented versions, for instance, converts “ÉéÜüÄäÖö” into “EeUuAaOo”. The function will handle any accented character for which there exists an HTML entity in PHP’s translation table (i.e. pretty much any and all characters). Credits go to jennings at trad dot uji dot es for the original version of this incredibly useful little function. I used this function to good effect in “OpenSEF”:projects.

function unaccent($text) { static $search, $replace; if (!$search) { $search = $replace = array(); // Get the HTML entities table into an array $trans = get_html_translation_table(HTML_ENTITIES); // Go through the entity mappings one-by-one foreach ($trans as $literal => $entity) { // Make sure we don’t process any other characters // such as fractions, quotes etc: if (ord($literal) >= 192) { // Get the accented form of the letter $search[] = $literal; // Get e.g. ‘E’ from the string ‘É’ $replace[] = $entity1; } } } return str_replace($search, $replace, $text); }

Generate Unique Identifier

Generates a unique 32-character (128-bit) identifier, suitable for use e.g. as a record primary key in a database. Other than the fact that I’m using mt_rand instead of rand, this is straight from the “PHP manual”:http://php.net/manual/en/function.uniqid.php.

function generate_unid() { return md5(uniqid(mt_rand(), true)); }

Generate Random Password

Generates a secure, entirely random password of the specified length. Note that the generated password doesn’t include similar characters (e.g. i, l, o, 1, 0, I), facilitating reading it back correctly when written down on paper.

function generate_passwd($length = 16) { static $chars = ‘abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789’; $chars_len = strlen($chars); for ($i = 0; $i < $length; $i++) $password .= $chars[mt_rand(0, $chars_len – 1)]; return $password; }

Calculate Directory Size

Returns a recursively calculated estimate of the disk space used by a given directory. The function works by shelling out to the Unix ‘du’ command.

function du($directory) { if (!file_exists($directory)) return NULL; $du = popen(’/usr/bin/du -sb ‘ . $directory, ‘r’); $result = fgets($du, 256); pclose($du); list($result,) = explode(”\t”, $result); return intval($result); }

Format File Sizes

Given a byte size, returns a formatted string, e.g. 128M. Works all the way up to yottabytes (2^80^)

function filesize_format($size = 0, $decimals = 0) { static $units = array(’‘, ‘K’, ‘M’, ‘G’, ‘T’, ‘P’, ‘E’, ‘Z’, ‘Y’); if (empty($size)) return ‘-’; $unit = floor(log($size) / log(1024)); $value = round($size / pow(1024, $unit), $decimals); return number_format($value, $decimals) . $units[$unit]; }


Send E-mail Easily



This is an application-specific, extended version of PHP’s standard mail() function. It’s significantly more convenient to use since it accepts array parameters instead of the variously-delimited string arguments that the standard mail() requires. Specifically, the $to addresses can be provided as an associative array of names to e-mail addresses, the $message can be given as an array containing one element per line, and the optional $headers parameter also accepts an associative array.


function mail_ex($to, $subject, $message, $headers = array()) { $from = ‘no-reply@php.net’; // NOTE: application-specific!

// If the recipients have been given as an associative array, // pre-process them into RFC 2822-compliant strings if (is_array($to) && is_string(key($to))) { $to = array_map( create_function(’$k, $v’, ‘return “$k <$v>“;’), array_keys($to), array_values($to)); } // Convert recipients and message into strings, if necessary if (is_array($to)) $to = implode(’, ‘, $to); if (is_array($message)) $message = implode(”\n”, $message); // Combine default headers with user-provided headers $headers = array_merge( array( ‘From’ => $from, ‘Reply-To’ => $from, ‘X-Mailer’ => ‘PHP/’ . phpversion(), ), $headers); // Reduce the headers array to a CRLF-delimited string $headers = implode(”\r\n”, array_map( create_function(’$k, $v’, ‘return “$k: $v”;’), array_keys($headers), array_values($headers))); return mail($to, $subject, $message, $headers, “-f$from”); }

This snippet is also a good demonstration of using a somewhat functional programming style with PHP (not that PHP makes it particularly easy on the eyes).