PHP

See the PHP Manual for more information.

no posts found

Strings

Leading zeroes

// Prints a leading zero if `number` is a single digit.
echo sprintf('%02d', $number);

Include vars in strings

// Using an object.
$my_class = new stdClass();
$my_class->animal_action = 'jumps';

echo "The quick brown fox $my_class->animal_action over the lazy dog.\n";

// Using an array.
$my_array = [
    'animal_action' => 'jumps'
];

echo "The quick brown fox {$my_array['animal_action']} over the lazy dog.\n";

// Using mixed array and object.
$my_class = new stdClass();
$my_class->animal_actions[] = 'jumps';

echo "The quick brown fox {$my_class->animal_actions[0]} over the lazy dog.\n";

Arrays

Define an array

// Define an array.
$my_array = [a,b,c,d];

// Define an array (the old standard way < php 5.3).
$my_array = array(a,b,c,d);

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);

Objects and Classes

In Object-Oriented Programming a container called a class holds a collection of functions (called methods when they are in a class). A class does nothing until an instance of it is created (instantiated). Once an instance of a class has been created the methods can be used. A program can use any number of classes.

Defining a Class

<?php
class SimpleClass
{
    // Property declaration.
    public $var = 'a default value';

    // Constant declaration.
    const VAR_NAME = 'a value';

    // Class constructor method.
    public function __construct()
    {
        echo self::VAR_NAME;
    }

    // Method declaration.
    public function displayVar() {
        echo $this->var;
    }
}
?>

Instantiate a class

  • PHP library classes are always at the root so simply use one slash.
// Standard class instantiation.
$my_class_instance = new MyClass();
$my_class_instance = new child\MyChildClass();
$my_class_instance = new \MyRootLevelClass();

// Instantiate a new empty class
$my_empty_class_instance = new stdClass();
$my_empty_class_instance = new (object)[]; // Optionally as of PHP 5.4 

Instantiate a class dynamically

// Instantiate a class dynamically
$class_name = '\\Foo\\Bar\\MyClass';
$my_class_instance = new $class_name();

Convert an Object to an Array

$array = json_decode(json_encode($object), true);

Calling functions and methods

// Call a function programmatically
$func = 'my_function';
$func('param1'); // calls my_function('param1');
// Call a class method programmatically
$my_method_name = 'foo';
$my_class = new MyClass();
$my_class->$my_method_name(); // calls the MyClass->foo() method. 

Convert an object to an array

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

Autoloading

In order to instantiate (create an instance of) a class which is defined in a separate file, that file must be included or required into the file currently being executed.

no posts found

Control Structures

Ternary Operators

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

Alt Syntax (for views)

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon : and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

<?php if ($x == 1): ?>
    ...
<?php else: ?>
    ...
<?php endif; ?>
no posts found no posts found no posts found

Filter and Sanitize

filter_input

// Sanitize input
if (is_numeric($_POST[$post_key])) {
    $filtered_db_inputs[$post_key] = filter_input(INPUT_POST, $post_key, FILTER_SANITIZE_NUMBER_INT);
} else {
    $filtered_db_inputs[$post_key] = filter_input(INPUT_POST, $post_key, FILTER_SANITIZE_STRING);
}

Trimming

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"

Serializing

If your string contains a ", ', :, or ; character in any of the array values the serialization will get corrupted. In order to avoid this, always base64 encode and decode along with serializing.

// Safely serialize.
$safe_string_to_store = base64_encode(serialize($array));

// Safely  unserialize...
$array_restored_from_db = unserialize(base64_decode($array));

Concatenation

Using arrays

// Concatenate lines with an 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>
no posts found no posts found no posts found

HTML and DOM Parsing

DOMDocument

// Create a new DOMDocument object.
$dom = new DOMDocument; 
 
// Load the HTML page 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.
$my_div_obj = $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.
}

Remove HTML Tag Attribute

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

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

Get all image tags

preg_match_all('/]+>/i',$html, $result);
no posts found no posts found no posts found

Abbr Bytes

/**
 * Convert bytes to proper abbreviation.
 */
private function format_bytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 
    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow]; 
}
no posts found

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>

Headers and Redirects

301 Moved Permanently

<?php header("Location: http://domain.tld/new/location/", true, 301); ?>
no posts found