Member Login
Discussion

15 very useful PHP code snippets for PHP developers

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. 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

  1. $to = "viralpatel.net@gmail.com";
  2. $subject = "VIRALPATEL.net";
  3. $body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
  4. $headers = "From: Peter\r\n";
  5. $headers .= "Reply-To: info@yoursite.com\r\n";
  6. $headers .= "Return-Path: info@yoursite.com\r\n";
  7. $headers .= "X-Mailer: PHP5\n";
  8. $headers .= 'MIME-Version: 1.0' . "\n";
  9. $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  10. mail($to,$subject,$body,$headers);
  11. ?>

2. Base64 Encode and Decode String in PHP

  1. function base64url_encode($plainText) {
  2. $base64 = base64_encode($plainText);
  3. $base64url = strtr($base64, '+/=', '-_,');
  4. return $base64url;
  5. }
  6. function base64url_decode($plainText) {
  7. $base64url = strtr($plainText, '-_,', '+/=');
  8. $base64 = base64_decode($base64url);
  9. return $base64;
  10. }

3. Get Remote IP Address in PHP

  1. function getRemoteIPAddress() {
  2. $ip = $_SERVER['REMOTE_ADDR'];
  3. return $ip;
  4. }

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.

  1. function getRealIPAddr()
  2. {
  3. if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
  4. {
  5. $ip=$_SERVER['HTTP_CLIENT_IP'];
  6. }
  7. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
  8. {
  9. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  10. }
  11. else
  12. {
  13. $ip=$_SERVER['REMOTE_ADDR'];
  14. }
  15. return $ip;
  16. }

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”

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

5. Email validation snippet in PHP

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

6. Parsing XML in easy way using PHP

Required Extension: SimpleXML

  1. //this is a sample xml string
  2. $xml_string="<?xml version='1.0'?>
  3. <moleculedb>
  4. <molecule name='Benzine'>
  5. <symbol>ben</symbol>
  6. <code>A</code>
  7. </molecule>
  8. <molecule name='Water'>
  9. <symbol>h2o</symbol>
  10. <code>K</code>
  11. </molecule>
  12. </moleculedb>";
  13. //load the xml string using simplexml function
  14. $xml = simplexml_load_string($xml_string);
  15. //loop through the each node of molecule
  16. foreach ($xml->molecule as $record)
  17. {
  18. //attribute are accessted by
  19. echo $record['name'], '  ';
  20. //node are accessted by -> operator
  21. echo $record->symbol, '  ';
  22. echo $record->code, '<br />';
  23. }

7. Database Connection in PHP

  1. <?php
  2. if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
  3. $dbHost = "localhost"; //Location Of Database usually its localhost
  4. $dbUser = "xxxx"; //Database User Name
  5. $dbPass = "xxxx"; //Database Password
  6. $dbDatabase = "xxxx"; //Database Name
  7. $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
  8. mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
  9. # This function will send an imitation 404 page if the user
  10. # types in this files filename into the address bar.
  11. # only files connecting with in the same directory as this
  12. # file will be able to use it as well.
  13. function send_404()
  14. {
  15. header('HTTP/1.x 404 Not Found');
  16. print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
  17. '<html><head>'."n".
  18. '<title>404 Not Found</title>'."n".
  19. '</head><body>'."n".
  20. '<h1>Not Found</h1>'."n".
  21. '<p>The requested URL '.
  22. str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
  23. ' was not found on this server.</p>'."n".
  24. '</body></html>'."n";
  25. exit;
  26. }
  27. # In any file you want to connect to the database,
  28. and in this case we will name this file db.php
  29. # just add this line of php code (without the pound sign):
  30. include"db.php";
  31. ?>

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.

  1. $json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
  2. echo json_encode($json_data);

Following code will parse the JSON data into PHP arrays.

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

9. Process MySQL Timestamp in PHP

  1. $query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
  2. $records = mysql_query($query) or die(mysql_error());
  3. while($row = mysql_fetch_array($records))
  4. {
  5. echo $row;
  6. }

10. Generate An Authentication Code in PHP

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

  1. <?php
  2. # This particular code will generate a random string
  3. # that is 25 charicters long 25 comes from the number
  4. # that is in the for loop
  5. $string = "abcdefghijklmnopqrstuvwxyz0123456789";
  6. for($i=0;$i<25;$i++){
  7. $pos = rand(0,36);
  8. $str .= $string{$pos};
  9. }
  10. echo $str;
  11. # If you have a database you can save the string in
  12. # there, and send the user an email with the code in
  13. # it they then can click a link or copy the code
  14. and you can then verify that that is the correct email
  15. or verify what ever you want to verify
  16. ?>

11. Date format validation in PHP

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

  1. function checkDateFormat($date)
  2. {
  3. //match the format of the date
  4. if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
  5. {
  6. //check weather the date is valid of not
  7. if(checkdate($parts[2],$parts[3],$parts[1]))
  8. return true;
  9. else
  10. return false;
  11. }
  12. else
  13. return false;
  14. }

12. HTTP Redirection in PHP

  1. <?php
  2. if (!emptyempty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
  3. $uri = 'https://'; / what?
  4. else {
  5. $uri = 'http://'; / what?
  6. }
  7. $uri .= $_SERVER['HTTP_HOST'];
  8. header('Location: 'http://you_stuff/url.php'); // stick your url here
  9. exit;