PHP: General

passing variables via url

Pass variables to a page using the question mark, for example mypage.php?value=hello. Access these variables with the _GET command.

string replace

find and replace pattern in a string.

send email

Send an email from PHP - one line example.

redirect browser

Using the php header function, a browser can be redirected to another page.

get current filename as variable

Sometimes you need just the filename of the current script, without the path. This snippet does just that using the SCRIPT_NAME and explode function.

email validation, simple

Validate an email address - returns TRUE or FALSE. Checks format only, does not use any networking functions to verify the account actually exists.

ban / block IP addresses

This example gets the users IP address and exits the page if it matches a banned number.

get current page URL

Often used for form actions, the variable $PHP_SELF has changed with recent versions, and now must be accessed using the _SERVER array of pre-defined variables.

form action - detect form post

There are several ways to process a php form. This example looks for the existance (regardless of value) of the Submit _POST variable.

generate random number

Generate a random number using mt_rand. From the php documentation- "If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5, 15)."

force cookies, disable php sessid in URL

This commands disables php from rewriting URLs to add a phpsessid, and forces the use of cookie sessions instead. Using cookies is largely thought of as the preferred way to use sessions - both more secure and better for SEO. This can be accomplished by setting the appropriate values in php.ini, or at runtime. This snippet shows a runtime example:

show referring URL

Grabs the referring URL - get the HTTP_REFERER and save it to a variable.

include a file with error reporting

Sometimes you want to be able to give some feedback if a PHP include has failed. Here is a version using the fopen command, which can search the include path.

form handling example - simple

This example shows a very simple form together with the form handling process on a single page.

Permanent 301 Redirect - Basic

If the URL of a page is changed, a 301 permanent redirect should be created to point visitors to the new location and most importantly: help preserve existing search engine ranking. 301's are usually setup via the .htaccess file, but you can also use a .php script

Define A Constant

Once a constant has been defined it cannot be changed. By convention constants are usually written in all capitals. To define, see the following example:

disable PHP Timeout

By default, php scripts will timeout after 30 seconds. While not recommended, you can override this setting with the set_time_limit() command. Useful if you are using php to process multiple files, etc.

convert string to uppercase / capitals

PHP provides a simple function to convert all letters to uppercase / captials: strtoupper();

Set MYSQL Connection Timeout Period

By default, PHP waits for 60 seconds to timeout a mySQL connection. This is way too long, and can cause PHP to timeout or hang. The easy and undocumented fix is to set the default timeout period. Luckily you can do this at runtime.

PHP: Control Structures

switch - integers

php switch example

switch - strings

switch example using strings

foreach loop

simple php example of a for-each loop, useful for iterating over lists and objects arrays.

for loop - simple

for loop - basic control structure. This example loops until the variable hits 10 and then breaks out.

if else example

basic example of an if then else control structure.

Foreach with empty array

This is a gem. PHP's foreach iterator will throw an error if an empty or non-array is passed. To return a null result instead, typecast the input variable using array().

PHP: Objects

object declaration

declare an object in php. This example also shows how to pass a value to the object when created.

get PHP object variables as an array

The get_object_vars() PHP function is exactly what you need to get a list of object variables. This function returns an associative array of defined object properties for the specified PHP object.

PHP: Strings

Safely display quotes and other special characters

This example uses the htmlspecialchars() command to convert all special characters in a string to "browser safe" versions. This is useful for displaying double quotes in a form's textfield and preventing user text from containing HTML markup during form input.

Format Numbers

PHP offers an easy function for displaying formatted numbers. When called with one paramater, the number_format() function returns a string representing the original number with grouped thousands

format date to mysql datetime

Convert the current date and time to MySQL datetime format using PHP's date() function.

String Starts With..

Checks whether string begins with given string.

Strip leading comma from a string

This snippet removes the leading comma (if there is one)from a string using the ltrim command.

get first character in a string

Return the first character in a string.

Truncate String Function

This function uses strlen() to truncate a long string and return a shortened version.

find string

Search and detect the presence of a string inside another string using the strpos() command. This example from the php.net website:

count number of words in a string

Count the number of elements in a string using the count() and explode() commands. By specifying a delimiter you can also use this technique to break apart file paths and comma seperated lists.

extract numbers from string

Extract numbers from a string (remove all letters, symbols, and other characters.) Using ereg_replace, we specify that numbers 0-9 should NOT be replaced, and therefore removing letters, symbols, and everything else.

extract filename from a full path string

Easily return the filename component of a path with the built-in PHP basename() function. Useful for splitting a string path to get the filename.

return directory component

Find the directory componenet of a filename using the PHP function dirname().

Convert string to UTF-8 for MySQL

This very useful function will convert a string to utf-8, allowing you update a MySQL table that has collation conflicts. For example if you've imported a latin1 charset and need to display it in utf-8

File to String - Simple

Reading a file to a string couldn't be easier than using the file_get_contents() function. Simple pass the name of the file (with path) and optional parameters (see documentation link).

PHP: Arrays

array declaration

simple php array declaration:

search array - find in array

Search an array to find a specific value.

Create array from comma separated list

Use the PHP Explode() command to create an array from a comma separated list. By changing the delimiter you can convert tab separated, newline separated, etc..

Create comma separated list from array

Use the implode() command to create a comma separated list from an array.

Return random array element

Return a random array element using the array_rand() function.

PHP: Image Manipulation

Get Image Size

The PHP function: getimagesize() is an easy way to find the size of an image. From the official documentation: The getimagesize() function will determine the size of any GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP, IFF, JP2, JPX, JB2, JPC, XBM, or WBMP image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML tag. If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will return FALSE and generate an error of level E_WARNING.

ImageThumb (Full Script)

ImageThumb is a small piece of software written in the PHP language that lets you create thumbnails on the fly for a given image, whether it is local ore remote. Currently supported formats are GIF, PNG and JPEG. To use this script, you must have the GD library installed, and obiously a webserver capable of running PHP scripts.

PHP: File

read file to a string

Read a text file to a string variable using fgets.

write string to file

write string variable to a text file

check if a file or directory exists

To determine whether a file exists on the server, PHP has a simple function: file_exists(). This can also be used to determine if a directory exists.

Upload File

Simple example that shows how to upload a file using PHP. Both the form and the data processer are on the same page. Configure the upload path and the max file size as per your requirements.

read file to array

This simple PHP example shows how to read a text file into an array, with each line of the file as a seperate element.

Open a directory

This simple function generates a select form element for all files of a given directory. Use this function together with the "Universal downloader" on this site. The function is modified to work with "register_globals = off "(since version 1.01). I changed the last version (1.02) to make this function more flexible. Use the modified function in forms to update dynamic image names in a database table.

PHP: Smarty

date and time formatting

The Smarty date_format function returns a formatted string showing date, time and/or seconds.