15 very useful PHP code snippets for PHP developers

php-logoFollowing 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. You may also want to comment on any of the code or also you can share your code snippet through comment section if you think it may be useful for others.

1. Send Mail using mail function in PHP

$to = "[email protected]";
$subject = "VIRALPATEL.net";
$body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$body,$headers);
?> 

2. Base64 Encode and Decode String in PHP

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

3. Get Remote IP Address in PHP

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

The above code will not work in case your client is behind proxy server. In that case use below function to get real IP address of client.

function getRealIPAddr()
{
	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;
}

4. Seconds to String

This function will return the duration of the given time period in days, hours, minutes and seconds.
e.g. secsToStr(1234567) would return “14 days, 6 hours, 56 minutes, 7 seconds”

function secsToStr($secs) {
	if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
	if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
	if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
	$r.=$secs.' second';if($secs<>1){$r.='s';}
	return $r;
}

5. Email validation snippet in PHP

$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&amp;'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
	echo 'This is a valid email.';
} else{
	echo 'This is an invalid email.';
} 

6. Parsing XML in easy way using PHP

Required Extension: SimpleXML

//this is a sample xml string
$xml_string="<?xml version='1.0'?>
<moleculedb>
    <molecule name='Benzine'>
        <symbol>ben</symbol>
        <code>A</code>
    </molecule>
    <molecule name='Water'>
        <symbol>h2o</symbol>
        <code>K</code>
    </molecule>
</moleculedb>";

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

//loop through the each node of molecule
foreach ($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

<?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name

$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("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_404()
{
    header('HTTP/1.x 404 Not Found');
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
    '<html><head>'."n".
    '<title>404 Not Found</title>'."n".
    '</head><body>'."n".
    '<h1>Not Found</h1>'."n".
    '<p>The requested URL '.
    str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
    ' was not found on this server.</p>'."n".
    '</body></html>'."n";
    exit;
}

# 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 (without 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 ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);

Following code will parse the JSON data into PHP arrays.

$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
//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.

<?php
# 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 = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
    $pos = rand(0,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 checkDateFormat($date)
{
	//match the format of the date
	if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
	{
		//check weather the date is valid of not
		if(checkdate($parts[2],$parts[3],$parts[1]))
			return true;
		else
		return false;
	}
	else
		return false;
}

12. HTTP Redirection in PHP

<?php
	header('Location: http://you_stuff/url.php'); // stick your url here
?>

13. Directory Listing in PHP

<?php
 
function list_files($dir)
{
	if(is_dir($dir))
  	{
  		if($handle = opendir($dir))
  		{
  			while(($file = readdir($handle)) !== false)
  			{
  				if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db"/*pesky windows, images..*/)
  				{
  					echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
  				}
  			}
  			closedir($handle);
  		}
	}
}

/*
To use:
 
<?php
	list_files("images/");
?>
*/
?>

14. Browser Detection script in PHP

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

15. Unzip a Zip File

<?php
    function unzip($location,$newLocation){
        if(exec("unzip $location",$arr)){
            mkdir($newLocation);
            for($i = 1;$i< count($arr);$i++){
                $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
                copy($location.'/'.$file,$newLocation.'/'.$file);
                unlink($location.'/'.$file);
            }
            return TRUE;
        }else{
            return FALSE;
        }
    }
?> 
//Use the code as following:
<?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
    echo 'Success!';
else
    echo 'Error';
?>

How you like this small collection of PHP code snippets. You may want to paste your code snippet in the comment section below and share it with others. :)

Get our Articles via Email. Enter your email address.

You may also like...

62 Comments

  1. Pourya says:

    I haven’t done PHP for a long time but these are Very nice! should be really useful for people doing PHP thnx :-)

  2. Viral Patel says:

    @pourya: thanks for the comment. Please feel free to share some more php code snippets.

    • nice to your website code of php and learn to easy ……………thanx……for……….

  3. Wolfgang says:

    Some of your code snippets could be solved in a much better way:

    # 4:
    list($d, $h, $m, $s) = explode(\" \",gmdate(\’j H i s\’,12345678));
    return ($d-1).\" days $h hour $m minutes $s seconds\"; // -1 @ days because date starts with jan 1st ;-)

    # 11:
    Use php build in function checkdate()
    http://php.net/manual/en/function.checkdate.php

    # 15:
    Use php build in function ziparchive::extractto()
    http://php.net/manual/en/function.ziparchive-extractto.php

  4. lo says:

    i just skimmed this blogpost really quick, but for #13 u should use the SPL DirectoryIterator:
    http://de.php.net/directoryiterator

    and for the other snippets i recommend to use an already existing library/framework (pear, zf, symfony, …) ;)

  5. Viral Patel says:

    @wolfgang: thanks a lot for the updates. I will sure look at the code and try to add more in this list.

    @lo: thanks to you too for the tip. i know these snippets and the updates by people who have commented will of great help to php newbies.

  6. cletus says:

    The email filter is poor and ignores a PHP standard function:

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // it’s valid
    }

  7. Kumar says:

    For MySQL Connection in PHP we have one more function mysql_pconnect() which we can use when we don\’t need connect to DB server each time. Having the same reference to connect again. For more details http://in.php.net/function.mysql-pconnect

  8. Viral Patel says:

    @kumar: thanks for the useful comment. mysql_pconnect() indeed is a better option to connect to mysql in php.

  9. ubuntuverse says:

    thanks for the good post! imho is using glob (http://at2.php.net/glob) better for the directory listing.

  10. Bogdan Popa says:

    Tip 11:
    foreach(glob(“*”) as $f)
    if (is_dir($f))
    echo $f;

    Is much simpler :).

  11. Bogdan Popa says:

    Tip 13, sorry.

  12. Don\’t want to sound too cynical, but I\’m not really impressed with this list. Some of the snippets do not add anything to the information available in the PHP (or MySQL) manual (#1, #6, #7, #8, #9, #14), for others you do not specify what is interesting about this snippet.

    #2: Explain what you\’re doing (encode a string using base64 for the use in an URL) and why base64_encode / _decode doesn\’t cut it.
    #3: Creating a function to return an existing variable obscures code and makes your code run slower. Why not just use $_SERVER[\’REMOTE_ADDR\’] directly in your code? (or at least return the value directly without re-assigning it to another variable). The getRealIPAddr() function _is_ useful, but why would you want to use the getRemoteIPAddress() if you have the getRealIPAddr() function?
    #4: If you post code snippets to help people write code, make sure they can read and understand your code (personally I think you\’re code should always be readable and understandable but that\’s your choice ;)).
    #5: See the other comment about filter_var()
    #7: Never ever put database connection details inside your webroot! (imagine you update your server with an error in your PHP config and all PHP files are served as plain text).
    #9: Not really a PHP code snippet is it?
    #12: Eh what? What\’s up with the $uri variable you don\’t use?
    #13: I agree with the other comments to use the SPL directory iterator or scandir or glob. When you use glob use the GLOB_ONLYDIR flag instead of checking if the path is a directory inside the loop. Another thing to be aware of when using glob is that it will return the complete path you specify (e.g. glob(\’./*\’) will return ./file1 and ./file2. glob(\’/path/*\’) will return /path/file1 and /path/file2.
    #15: Have a look at PHP\’s zip functions (http://php.net/manual/en/ref.zip.php)

    Don\’t get me wrong: I encourage you to post snippets that may be useful to others, just think a minute longer about what you\’ll be posting and make sure the examples solve a problem (i.e. aren\’t copy+paste from the manual) and are clear and understandable.

  13. Isaac Van Name says:

    Overall, I think the snippets were educational, whether they were exemplary or not (in some cases). They served a purpose in making us think of how we would solve the problems better or, in cases where newer programmers hadn’t been faced with the problem, in making us realize that we might have to solve them in a similar way to what was presented here.

    My only complaint was #10, which could’ve been solved more simply using the uniqid() function with an md5() of microtime(). Instant random string of a length you choose. :-)

    For those that were complaining about the email validation: For those of us that cannot chose the dev environment of our clients, we must often resort to a solution that supports both PHP4 and PHP5. As the filter functions were introduced in 5, this solution actually helps.

    The fact still remains, though… that these snippets were somewhat sloppy code. There’s a beauty in serving a purpose, and there’s a beauty in serving a purpose optimally. Hopefully, there will be a part 2 with a rewrite.

  14. butzi says:

    I think the list is generally ok. The primary focus was not to show perfect code, but just an entry into the language PHP at all. There will always be a way to optimize the code.
    So go on with these intoducing tutorials!

    If you want to try one of the scripts/functions above you can test some of them here: http://www.functions-online.com

  15. nmstudio says:

    Don’t just mindlessly copy-paste provided code. Some of provided snippets may create a serious vulnabilities on your site. For example snippet #14 may create XSS ( http://en.wikipedia.org/wiki/Cross-site_scripting ).
    Never trust the input you get from user.

  16. Darwin Santos says:

    Thanks for the list, very useful.

  17. pok says:

    #12 HTTP Redirection in PHP
    What is this ??? Doesn’t maen anything

  18. Ronald H. says:

    These are really great. I’m just greating into PHP, so every little bit helps. I really like this code. There almost like litte time savers. Thank You.

  19. hossein says:

    nice :)

  20. Jef says:

    Great snippets!

  21. Viral Patel says:

    @Ronald, @Hossein, @Jef… Thanks for the comment.. :)

  22. srisoftwarez says:

    Thanks man this is a great sample.. this will be very use-full for all developers.

  23. Mr Foo says:

    #14: Lose the single quote right before the “http”.

    • Viral Patel says:

      @Mr. Foo: I think you are pointing to Tip #12. I have corrected the typo error. Thanks

  24. babu says:

    hai this is really superb.
    regards
    babu.p

  25. Hardik says:

    Hey Viral,

    I wanna know is der a function thru which i can get client’s computer name and I.P address,
    Computer Name Must…
    whenever a client my web site his computer name shud be stored in my db…
    Thanx in Advance.

  26. Viral Patel says:

    @Hardik: Well I am not aware of such function in PHP. I think there is no HTTP header element which holds such data.
    Let me know in case you find a way to achieve this.

  27. Little Geek says:

    OK! i must say these are really good examples of useful handy php snippets. i have collected some snippets, it might be handy for others too. here is the link : http://www.alittlegeek.com/18-php-snippets-to-boost-your-development-speed/. i am thinking of using some of your snippets as a new post in my blog.

  28. Bill says:

    In regard to mysql_pconnect() vs mysql_connect(), be careful when taking advice. mysql_pconnect() is viewed by many as unneccessary and, in some cases, even a bad choice for typical database programmers. Persistant connections can be costly in terms of resources. For more info go here… http://efreedom.com/Question/1-247807/Mysql-Connect-VS-Mysql-Pconnect

  29. WebDev says:

    Hi Viral.

    Excellent Post.
    How can we create Thumbnail form uploaded image (JPG, GIF, PNG) on a fly?
    Please Help.

    • $h_old) {
      $rat=$w_old/$w;
      }
      else {
      $rat=$h_old/$h;
      }
      $w_new=round($w_old/$rat);
      $h_new=round($h_old/$rat);
      $new = imageCreateTrueColor($w_new, $h_new);
      imageCopyResized($new, $old, 0, 0, 0, 0, $w_new, $h_new, $w_old, $h_old);
      imageJpeg($new,””,”100″);
      }
      }
      ?>

      save the file as resize.php

      Use it in a way like this

      http://yoursite.com/resize.php?pic=/uploads/image.jpg

  30. Oglasi says:

    Nice post, i work on some php project and i’m using some of this snippets. Works very well. Thank you.

  31. tendai says:

    Useful tools indeed. thanks!

  32. Ali says:

    Really useful snippets, very helpful. Thank you.

  33. Moulika says:

    I want code how to send sms after user successfully registered in a website.

    Please Help me out of this.

    Thanks & Regards,
    Moulika.

  34. Sonu says:

    Hi,Can you guide me how to use IP address snippet.I don’t how to use it.Waiting for help…

  35. Ap says:

    Hi,

    Guide me how to stream audio, video in the web page using php any code snippet i will wait …..

  36. Credevator says:

    Helpful snippets,
    thnx
    keep posting

  37. freemz says:

    Very helpful snippets thank’s, and this is a good website where you can find more php snippets on all categories :
    http://www.codesphp.com

  38. Kevin says:

    Some good coding

  39. Ayan says:

    very useful scripts. I used some of this in my site.

  40. Santosh says:

    This blog very helpful,

  41. dany says:

    it’s work… thank you so much..

    this is support for html and add image for header mail ??
    thank..

  42. ankit says:

    thanks a lot for these scripts

  43. Jason says:

    These helped with a site I am working on. Thanks!

  44. Arvind says:

    i like Unzip a Zip File
    nice article…

  45. bhumit trivedi says:

    Hi !

    I have just started with php, I have installed WAMP but dont wht to start with ?

    any suggestions for the basic programs to starts with ……
    targeting to learn WAMP and PHP!

  46. alin says:

    i want to creat a inbox (messaging system) like facebook for my website in PHP. plz help with advice & php codeā€¦.

  47. alex says:

    can you add this login system made by me if you whish

    <?php
    include('../inc/db.inc.php');
    date_default_timezone_set('Europe/Rome');
    $data = date("d/m/Y H:i");
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    
    $user = trim(strip_tags(mysqli_real_escape_string($db,$_POST["username"])));
    $pass = trim(strip_tags(mysqli_real_escape_string($db,$_POST["password"])));
    $pass_enc = sha1($pass);
    
    if(filter_var($user, FILTER_SANITIZE_STRING) && filter_var($pass, FILTER_SANITIZE_STRING)) {
    	if(ctype_alnum($user)&&ctype_alnum($pass)){
    		$verificaDB = "SELECT username,password,email,attivo,ban FROM utenti WHERE username='$user' AND password='$pass_enc' LIMIT 1";
    		if ($stmt_login = mysqli_prepare($db, $verificaDB)) {
    			mysqli_stmt_execute($stmt_login);
    				mysqli_stmt_store_result($stmt_login);
    			 		if(mysqli_stmt_num_rows($stmt_login) == 1){
    			 			mysqli_stmt_bind_result($stmt_login, $u, $p, $em, $attivo, $ban);
    			 				while (mysqli_stmt_fetch($stmt_login)) {
           						  if($attivo == 1){
           						  	if($ban == 0){
           						  		session_start();
           						  		if($_SESSION["utente"] = $u){
           						  			$updDBS = mysqli_prepare($db,"UPDATE utenti SET ultimo_accesso = '$data',ultimo_ip='$ip' WHERE username='$u'");
    											mysqli_stmt_execute($updDBS);
    													mysqli_stmt_free_result($updDBS);
    														mysqli_stmt_close($updDBS);
           						  		}
           						  		
           						  	}else{
           						  		echo "questo account e stato banato";
           						  	}
    
           						  }else{
           						  	echo "il account non e attivo";
           						  }
        						}
    
    			 		}else{
    			 			echo 'username o password non corette';
    			 		}
    		mysqli_stmt_free_result($stmt_login);
    		mysqli_stmt_close($stmt_login);
    		}
    		mysqli_close($db);
    
    	}else{
    		echo 'caratteri invalidi';
    	}
    }
    ?> 
  48. sampath says:

    sir,
    Guide me how to create exam.php progam and also send php related codes

  49. mayur says:

    I want code how to send sms after user successfully registered in a website.
    Please Help me and send demo my alternet Id in there

  50. jay says:

    tryed all kinds couldnt get this working why?

    IP Page
    <?php
    // . Get Remote IP Address in PHP
    function getRemoteIPAddress() {
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
    }

    $a = getRemoteIPAddress();
    echo "$a";

    echo "”

    // The above code will not work in case your client is behind proxy server. In that case use below function to get real IP address of client.
    function getRealIPAddr()
    {
    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;
    }

    $b = getRealIPAddr();
    echo “$b”;

    echo “”

    ?>

  51. Avinash says:

    kindly send a code for pdf generation in php.

  52. I have personally used and tested some of this. For sure very useful in daily practice.

    • abc says:

      good one!

  53. Karthik Nair says:

    Dear Avinash

    try this for generate pdf using html & php

    http://www.fpdf.org/

  54. nitinn says:

    i need some help in mssql 2008 database connection in php i have tried some code bt cant connect n cant retive data from d table

  55. siddu says:

    how can we stop the form resubmission on click of ctrl+f5 for avoiding the insertion of duplicate record in database table using php and mysql–Thanks in advance

  56. LOKESH says:

    Dear sir I made php application for invoice generation wuth the wamp server. I can generate invoice by adding manually product name and generate invoice but now I want to use barcode scanner for reading product so I need code for barcode scanner and how barcode scanner work .

  57. Waseem Asgar says:

    Hey Siddu,
    Just look at my code for stop resubmit form value again and again.
    “1”, “message”=>”Invalid Submission”);
    }
    elseif($_POST[‘form_token’] != $_SESSION[‘form_token’])
    {
    $notification = array(“error”=>”1”, “message”=>”Access denied”);
    }
    else
    {
    //Write Your Code Here
    }
    }
    $form_token = uniqid();
    $_SESSION[‘form_token’] = $form_token;
    $categoryNameData = allCategoryName($conn)
    ?>

    //ADD THIS INPUT TYPE ANY WHERE INSIDE FORM
    <input type="hidden" name="form_token" value="” />

    Please like my page on facebook. http://www.facebook.com/whcommerce
    Thanks
    Waseem Asgar
    http://www.whcommerce.com

  58. Apenta says:

    Useful functions collection, thanks. But getRemoteIPAddress is not really accurate.

Leave a Reply

Your email address will not be published. Required fields are marked *