PHP

Report Errors

// Report all PHP errors.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

This alone doesn’t make PHP show parse errors. The only way to show parse errors is to set display_errors = on in the php.ini file.

Strings

Trim

Use trim, ltrim, and rtrim to remove substrings from the beginning and end of a string.

$string = ' _hello_ ';
$trimmed = trim( $string ); // Returns "_hello_"
echo trim( $trimmed, '_' ); // Returns "hello"

// Warning 'ltrim' and 'rtrim' remove all instances of all the characters passed
// to the function. It is not a string definition.
echo ltrim( $string, ' _' ); // Returns "hello_ "
echo = rtrim( $string, '_ ' ); // Returns " _hello"

Starts and Ends With

/**
 * Checks if a string starts with another string.
 */
function starts_with( $haystack, $needle )
{
    //return $needle === "" || strrpos( $haystack, $needle, -strlen( $haystack ) ) !== FALSE;
    return substr( $haystack, 0, strlen( $needle )) === $needle )
}
/**
 * Checks if a string ends with another string.
 */
function ends_with( $haystack, $needle )
{
    return $needle === ""
        || (
            ( $temp = strlen( $haystack ) - strlen( $needle ) ) >= 0
            && strpos( $haystack, $needle, $temp) !== FALSE
        )
    ;
}

Get Beginnings and Ends

$string = 'testers';

// Get the first character of a string.
$newString = substr( $string, 1 ); // returns "t"

// Get the first three characters of a string.
$newString = substr( $string, 3 ); // returns "tes"

// Get the last character of a string.
$newString = substr( $string, -1 ); // returns "s"

// Get the last three characters of a string.
$newString = substr( $string, -3 ); // returns "ers"

Remove Beginnings and Ends

$string = 'testers';

// Remove the first character from a string.
$newString = substr($string, 0, 1); // returns "esters"

// Remove the first three characters from a string.
$newString = substr($string, 0, -3); // returns "ters"

// Remove the last character from a string.
$newString = substr($string, 0, -1); // returns "tester"

// Remove the last three characters from a string.
$newString = substr($string, 0, -3); // returns "test"

Occurrences of a Substring

// Get everything after the last occurrence of the substring in a string.
function getAfterLastOccurance( $string, $substring )
{
    return array_pop(explode( $substring, $string));
}

Loop Over New Lines

foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    // do stuff with $line
} 

Shorthand / Ternary Operators

$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true.

Variables

Constants

// Define constants.
define("CONSTANT", "Hello world.");
echo CONSTANT; // Returns "Hello world."

Arrays

Get the last element of an array

$lastEl = array_pop( ( array_slice( $array, -1 ) ) );

Count the number of element in an array

$total = count( $array );

Convert an object to an array

function obj_to_array( $obj )
{
    return (array) $obj;
}

Objects and Classes

Instantiate a class

$myClassInstance = new MyClass();
$myClassInstance = new child\stdClass();
$myClassInstance = new /root/stdClass();

Instantiate a class dynamically

$className = '\\Foo\\Bar\\MyClass';
$classInstance = new $className();

Instantiate a new empty class

$myEmptyClassInstance = new stdClass();

Methods and Functions

Call a method programmatically

$my_method_name = 'foo';
$my_class = new MyClass();
$my_class->$my_method_name(); // calls the MyClass->foo() method. 

Call a function programmatically

$func = 'my_function';
$func('param1'); // calls my_function('param1');

Globals

Current Directory

//
// Get the absolute path to the directory containing the current working file.
var_dump(__DIR__); // Recommended fastest way, but only available for PHP >= 5.3.
var_dump(dirname(__FILE__));

// Example:
// Both methods produce exactly the same result:
// string '/home/squale/developpement/tests/temp' (length=37)

Concatenation

Output Content

// Concatenate lines and use an array to maintain line breaks.
function get_div( $content )
{
    $output = array();

    $output[] = '<div>';
    $output[] = $content;
    $output[] = '</div>';
    
    return implode("\n", $output);
}

// Example:
echo get_div( 'hello' );

// Outputs:
// <div>
// hello
// </div>

Time

Useful time functions.

$the_current_microtime = microtime(true);

Check If File Exists

$filename = $_SERVER['DOCUMENT_ROOT'] . 'images/myImage.png';

if( file_exists( $filename ))
{
     echo "The file $filename exists";
} else {
     echo "The file $filename does not exist";
}

URLs and Paths

Get the current URL

$url = 'http' .
    ( isset( $_SERVER['HTTPS'] ) ? 's' : '' ) .
    '://' .
    "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"
;

Get the parts of a URL

$url = 'http://username:password@hostname:9090/path?arg=value#anchor';

echo parse_url( $url, PHP_URL_SCHEME ); // Returns "http"
echo parse_url( $url, PHP_URL_USER ); // Returns "username"
echo parse_url( $url, PHP_URL_PASS ); // Returns "password"
echo parse_url( $url, PHP_URL_HOST ); // Returns "hostname"
echo parse_url( $url, PHP_URL_PORT ); // Returns ""
echo parse_url( $url, PHP_URL_PATH ); // Returns "/path"
echo parse_url( $url, PHP_URL_QUERY ); // Returns "arg=value"
echo parse_url( $url, PHP_URL_FRAGMENT ); // Returns "anchor"

// Get all the URL parts in an array.
$url_parts = parse_url( $url );

Get the parts of a path

$file_path = '/home/mydir/myfile.pdf';

echo pathinfo( $file_path, PATHINFO_DIRNAME); // Returns "/home/mydir"
echo pathinfo( $file_path, PATHINFO_BASENAME); // Returns "myfile.pdf"
echo pathinfo( $file_path, PATHINFO_EXTENSION); // Returns "pdf"
echo pathinfo( $file_path, PATHINFO_FILENAME); // Returns "myfile"

// Get all the path parts in an array.
$file_path_parts = pathinfo( $file_path );

Get the file extension

// This is faster than using pathinfo() or getting
// the value from array if you just need the ext.
$ext = substr(strrchr($filename, "."), 1);

HTML Parsing and Filtering

DOMDocument

PHP core comes with a very handy HTML parser called DOMDocument.

// Create a new DOMDocument object.
$dom = new DOMDocument; 
 
// Load the HTML content into the object.
$dom->loadHTML($html);

Once the HTML is loaded into the object, access nodes and child elements:

Get an element by it’s ID

$mydivObj = $dom->getElementById('mydiv');

Get all elements of a type

$anchors = $dom->getElementsByTagName('a'); 
foreach($anchors as $anchor)
{
    echo $dom->saveHTML( $anchor ); // Prints the text-only content of the anchor.
}

More Resources
Parse html DOM with DOMDocument

Remove Tag Attributes


function removeAttribute( $html, $attributeName )
{
    return preg_replace( '/(<[^>]+) ' . $attributeName . '=".*?"/i', '$1', $html );
}

echo removeAttribute( '<div style="color:#CCC;"></div>', 'style' ); // Prints '<div></div>'

Email

Email Address Validation

$email = "john.doe@example.com";

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}

Extract Email Address

Send Email

Iterate Files and Directories

/**
 * Converts a nested directory tree into a multidimensional array
 * structured to represent the nesting hierarchy of all
 * files and directories defined by '$startpath'.
 */
function get_recursive_dir_file_listings( $startpath )
{
    $listings_array = array();

    $raw_listings = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator( $startpath ),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($raw_listings as $splFileInfo)
    {
        if( $splFileInfo->isDir() )
        {
            $path = array( $splFileInfo->getFilename() => array() );
        }
        else
        {
            $path = array( $splFileInfo->getFilename() ); 
        }

        for( $depth = $raw_listings->getDepth() - 1; $depth >= 0; $depth-- )
        {
           $path = array( $raw_listings->getSubIterator( $depth )->current()->getFilename() => $path ); 
        } 

        $listings_array = array_merge_recursive( $listings_array, $path ); 
    } 

    return $listings_array;
}

// Example:
// This will print an array containing the contents of
// the current directory and everything under it.

print_r( get_recursive_dir_file_listings( __DIR__ ) ) ;

Server Configs

Bootstrap a PHP App

Route all requests the server to one index.php file. This technique is known as bootstrapping. It transfers the routing responsibility from the web server to the app.

The first step is to setup an Apache virtual host which will follow SymLinks and allow overrides from mod rewrite.

# httpd.conf
<VirtualHost *>
    ServerName mydomain.com
    DocumentRoot "/abs/path/to/mywebroot"
    <Directory />
        Options Indexes FollowSymLinks
        AllowOverride All
    </Directory>
</VirtualHost>

A .htaccess file must exist in the same directory as the index.php file.

# .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)/$ /$1 [L,R=301] # This enforces NO trailing slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>