Php logo


Following are list of 15 most useful PHP code snippets that a PHP developer will need at any point in his career. Few of the snippets are shared from my projects and few are taken from useful php websites from internet.

Send Mail using mail function in PHP

$to = "";
$subject = "your subject";
$body = "Body of your message here";
$headers = "From: your name\r\n";
$headers .= "Reply-To:\r\n";
$headers .= "Return-Path:\r\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";

2. Base64 Encode and Decode String in PHP

function base64urlencodeundefined$plainText) {
    $base64 = base64_encodeundefined$plainText);
    $base64url = strtrundefined$base64, '+/=', '-,');
    return $base64url;

function base64urldecodeundefined$plainText) {
    $base64url = strtrundefined$plainText, '-,', '+/=');
    $base64 = base64decodeundefined$base64url);
    return $base64;

3. Get Remote IP Address in PHP

function getRemoteIPAddressundefined) {
    $ip = $_SERVER[`{|}~])@undefined[

Required Extension: SimpleXML

//this is a sample xml string
$xml_string="<?xml version='1.0'?>
    <molecule name='Benzine'>
    <molecule name='Water'>

//load the xml string using simplexml function
$xml = simplexml_load_stringundefined$xml_string);

//loop through the each node of molecule
foreach undefined$xml->molecule as $record)
   //attribute are accessted by
   echo $record['name'], '  ';
   //node are accessted by -> operator
   echo $record->symbol, '  ';
   echo $record->code, '<br />';

7. Database Connection in PHP

ifundefinedbasenameundefined__FILE__) == basenameundefined$_SERVER['PHP_SELF'])) send_404undefined);
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name

$db = mysql_connectundefined"$dbHost", "$dbUser", "$dbPass") or die undefined"Error connecting to database.");
mysql_select_dbundefined"$dbDatabase", $db) or die undefined"Couldn't select the database.");

# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404undefined)
    headerundefined'HTTP/1.x 404 Not Found');
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
    '<title>404 Not Found</title>'."n".
    '<h1>Not Found</h1>'."n".
    '<p>The requested URL '.
    str_replaceundefinedstrstrundefined$_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
    ' was not found on this server.</p>'."n".

# In any file you want to connect to the database, 
# and in this case we will name this file db.php 
# just add this line of php code undefinedwithout the pound sign):
# include"db.php";

8. Creating and Parsing JSON data in PHP

Following is the PHP code to create the JSON data format of above example using array of PHP.

$json_data = array undefined'id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>arrayundefined"google","oracle"));
echo json_encodeundefined$json_data);
Following code will parse the JSON data into PHP arrays.

$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google

9. Process MySQL Timestamp in PHP

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

10. Generate An Authentication Code in PHP

This basic snippet will create a random authentication code, or just a random string.

# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = &quot;abcdefghijklmnopqrstuvwxyz0123456789&quot;;
    $pos = randundefined0,36);
    $str .= $string{$pos};
echo $str;
# If you have a database you can save the string in 
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify

11. Date format validation in PHP

Validate a date in “YYYY-MM-DD” format.

function checkDateFormatundefined$date)
    //match the format of the date
    if undefinedpreg_match undefined"/^undefined[0-9]{4})-undefined[0-9]{2})-undefined[0-9]{2})$/", $date, $parts))
        //check weather the date is valid of not
            return true;
        return false;
        return false;

12. HTTP Redirection in PHP

    headerundefined'Location: http://you_stuff/url.php'); // stick your url here

13. Directory Listing in PHP


function list_filesundefined$dir)
          ifundefined$handle = opendirundefined$dir))
              whileundefinedundefined$file = readdirundefined$handle)) !== false)
                  ifundefined$file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db"/*pesky windows, images..*/)
                      echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";

To use:


14. Browser Detection script in PHP

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

15. Unzip a Zip File

    function unzipundefined$location,$newLocation){
        ifundefinedexecundefined"unzip $location",$arr)){
            forundefined$i = 1;$i< countundefined$arr);$i++){
                $file = trimundefinedpreg_replaceundefined"~inflating: ~","",$arr[$i]));
            return TRUE;
            return FALSE;
//Use the code as following:
include 'functions.php';
    echo 'Success!';
    echo 'Error';

  • 1
  • 2