15绝妙PHP代码片段

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.   
  7. function base64url_decode($plainText) {  
  8.     $base64url = strtr($plainText'-_,''+/=');  
  9.     $base64 = base64_decode($base64url);  
  10.     return $base64;  
  11. }   

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.   
  14. //load the xml string using simplexml function  
  15. $xml = simplexml_load_string($xml_string);  
  16.   
  17. //loop through the each node of molecule  
  18. foreach ($xml->molecule as $record)  
  19. {  
  20.    //attribute are accessted by  
  21.    echo $record['name'], '  ';  
  22.    //node are accessted by -> operator  
  23.    echo $record->symbol, '  ';  
  24.    echo $record->code, '<br />';  
  25. }  

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

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($queryor 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;  
  10. ?>  

13. Directory Listing in PHP

  1. <?php  
  2.   
  3. function list_files($dir)  
  4. {  
  5.     if(is_dir($dir))  
  6.     {  
  7.         if($handle = opendir($dir))  
  8.         {  
  9.             while(($file = readdir($handle)) !== false)  
  10.             {  
  11.                 if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)  
  12.                 {  
  13.                     echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";  
  14.                 }  
  15.             }  
  16.             closedir($handle);  
  17.         }  
  18.     }  
  19. }  
  20.   
  21. /* 
  22. To use: 
  23.  
  24. <?php 
  25.     list_files("images/"); 
  26. ?> 
  27. */  
  28. ?>  

14. Browser Detection script in PHP

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

15. Unzip a Zip File

  1. <?php  
  2.     function unzip($location,$newLocation){  
  3.         if(exec("unzip $location",$arr)){  
  4.             mkdir($newLocation);  
  5.             for($i = 1;$icount($arr);$i++){  
  6.                 $file = trim(preg_replace("~inflating: ~","",$arr[$i]));  
  7.                 copy($location.'/'.$file,$newLocation.'/'.$file);  
  8.                 unlink($location.'/'.$file);  
  9.             }  
  10.             return TRUE;  
  11.         }else{  
  12.             return FALSE;  
  13.         }  
  14.     }  
  15. ?>  
  16. //Use the code as following:  
  17. <?php  
  18. include 'functions.php';  
  19. if(unzip('zipedfiles/test.zip','unziped/myNewZip'))  
  20.     echo 'Success!';  
  21. else  
  22.     echo 'Error';  
  23. ?>