10 Useful PHP Code Snippets

June 14th, 2012 Leave a comment
Like the article?
PHP Code Snippets

Whether you are just learning how to write PHP or you are a veteran developer, you soon learn that there are things you do or situations that you encounter often. These 10 snippets provide a broad range of useful elements that you will often need to use as you write PHP applications. I hope you will find them useful and, if kept as a cheat-sheet, you can refer back to it at any time without having to do a lot of internet searching for the answer.

1. Getting a Remote IP Address

A quick and easy way to get the IP address of a client that is accessing your page:

function getRemoteIPAddress() {
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;

Very simple but ineffective if your client is behind a proxy server. If you have reason to believe this or you just want to be more accurate, use this:

function getRealIPAddress() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) { // check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;

2. Get the MySQL Timestamp

You often will want to fetch the timestamp of a particular row or set of rows. This quick query will return them.

$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records)) {
    echo $row;

3. Validate Date Format

Since we often use forms in PHP, you will want to validate that the date the user entered is in the correct YYYY-MM-DD format. This snippet will do just that!

function checkDateFormat($date) {
	// match the format of the date
	if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
		// check whether the date is valid of not
		if (checkdate($parts[2], $parts[3], $parts[1])) {
			return true;
		} else {
			return false;
	} else {
		return false;

You could also use the built-in checkdate() function that takes in a month, day and year as integers and checks if the date is valid as well as considers if each element is properly defined.

var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));

This function returns a boolean based on whether or not the date is valid, like this:


4. HTTP Redirection

Want to send your user to a different page they have landed on? Use this little snippet to add a redirection to the header of the request and send them to a different URL.

header('Location: http://www.yoursite.com/page.php');

5. Sending Email

Being able to send email using our PHP scripts is a common function. The hardest part of this is setting up the different items needed and the headers to process the email correctly. Here is a snippet you can use as a template:

$to = "someone@domain.com";
$subject = "Your Subject here";
$body = "Body of your message here you can use HTML too. e.g. <br><b> Bold </b>";
$headers = "From: You\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.com\r\n";
$headers .= "X-Mailer: PHP\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $body, $headers);

Once you have your email all set up, calling the mail function with all of the needed arguments will send your message.

6. Encode and Decode Base64 Strings

Base64 strings have all kinds of uses in PHP from saving image data to ensuring the binary data can be transported correctly. In this snippet we are encoding and decoding a Base64 URL.

function base64url_encode($plainText) {
    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
function base64url_decode($plainText) {
    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;

You can check if a string is valid Base64 encoded by using the base64_decode function. For example:

if (base64_decode($mystring, true)) {
    // is valid
} else {
    // not valid

7. Creating and Parsing JSON Data

JSON, or JavaScript Object Notation is a data-interchange format. You may find yourself using JSON with PHP to send data as an object or as a serialization/deserialization solution. This snippet creates the JSON data format into an array.

$json_data = array ('id'=>1,'name'=>"John",'country'=>'Canada',"work"=>array("Google","Oracle"));
echo json_encode($json_data);

This snippet parses the JSON into a PHP array:

$json_string='{"id":1,"name":"John","country":"Canada","work":["Google","Oracle"]} ';

// print the parsed data
echo $obj->name; //displays John
echo $obj->work[0]; //displays Google

8. Detect the User’s Browser

Since we often need to have different behaviors based on the user’s browser, or you just want this information for metric purposes, getting the user agent is simple:

$useragent = $_SERVER ['HTTP_USER_AGENT'];
echo "<b>Your User Agent is</b>: " . $useragent;

However, this will not work if the user is actively masking their agent with browser add-ons or other tools. There is no way to determine if the user agent is being spoofed.

9. Display the Source of Web Pages

This is a useful trick when browsing the source code of pages or helping co-workers with their web development projects. This snippet will display the source code of the given page, with line numbers:

$lines = file('http://google.com/');
foreach ($lines as $line_num => $line) {
	// loop thru each line and prepend line numbers
	echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";

10. Adjust the Server Time

When working in hosted or virtual environments we often have servers in different time-zones. This can be bad when displaying or using the current time, such as inserting a timestamp for a transaction. Here is how to adjust your server time to a different time zone:

$now = date('Y-m-d-G');
$now = strftime("%Y-%m-%d-%H", strtotime("$now -8 hours"));

Just add or subtract as needed to get the correct offset.

I hope you have enjoyed this list of PHP snippets and will find them useful as you progress on your journey through PHP. Remember to keep this list handy since many of these operations are performed regularly in your applications. I am sure you will also find many more you can add to this list.

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!