PHP some useful custom function collection

Source: Internet
Author: User
Tags explode extract zip file ziparchive

1. PHP can read random strings

This code creates a readable string that is closer to the word in the dictionary, and is practical and has password validation capabilities.

/************** * @length-length of random string (must be a multiple of 2) **************/function Readable_random_stri Ng ($length = 6) {     $conso =array ("B", "C", "D", "F", "G", "H", "J", "K", "L",     "M", "N", "P", "R", "s", "T", "V", "w", "X", " Y "," z ");     $vocal =array ("A", "E", "I", "O", "U");     $password = "";     Srand (Double) microtime () *1000000);     $max = $length/2;     for ($i =1; $i <= $max; $i + +)     {     $password. = $conso [Rand (0,19)];     $password. = $vocal [Rand (0,4)];     }     
2. PHP generates a random string

If you do not need a readable string, use this function instead to create a random string, as a random password for the user, and so on.

/************* *@l-length of random String * * function Generate_rand ($l) {   $c = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";   Srand (Double) microtime () *1000000);   for ($i =0; $i < $l; $i + +) {       $rand. = $c [Rand ()%strlen ($c)];   }   
3. PHP encoded e-mail address

With this code, any e-mail address can be encoded as an HTML character entity to prevent it from being collected by the spam program.

function Encode_email ($email = ' [email protected] ', $linkText = ' contact Us ', $attrs = ' class= ' Emailencoder "') {//R     Emplazar Aroba y puntos $email = str_replace (' @ ', ' @ ', $email);     $email = Str_replace ('. ', '. ', $email);        $email = Str_split ($email, 5);     $linkText = Str_replace (' @ ', ' @ ', $linkText);     $linkText = Str_replace ('. ', '. ', $linkText);        $linkText = Str_split ($linkText, 5);     $part 1 = ' <a href= ' ma ';     $part 2 = ' Ilto: '; $part 3 = ' "'.     $attrs. ' > ';        $part 4 = ' </a> ';     $encoded = ' <script type= ' Text/javascript > ';     $encoded. = "document.write (' $part 1 ');";     $encoded. = "document.write (' $part 2 ');";     foreach ($email as $e) {$encoded. = "document.write (' $e ');";     } $encoded. = "document.write (' $part 3 ');";     foreach ($linkText as $l) {$encoded. = "document.write (' $l ');";     } $encoded. = "document.write (' $part 4 ');";        $encoded. = ' </script> '; Return $enCoded  }
4. PHP Verification Email Address

e-mail validation is perhaps the most common form validation in Web pages, which, in addition to verifying e-mail addresses, also has the option of checking the MX records in the DNS that the mail domain belongs to, making the message verification feature more powerful.

function Is_valid_email ($email, $test _mx = False) {     if (eregi ("^ (_a-z0-9-]+) (\.[ _a-z0-9-]+) *@ ([a-z0-9-]+) (\.[ a-z0-9-]+) * (\.[ a-z]{2,4}) $ ", $email))         if ($test _mx)         {             list ($username, $domain) = Split (" @ ", $email);             Return Getmxrr ($domain, $mxrecords);         }         else             return true;     Else         
5. PHP Lists directory contents
function List_files ($dir) {     if (Is_dir ($dir))     {         if ($handle = Opendir ($dir))         {while             ($file = Readdir ($handle))!== false)             {                 if ($file! = "." && $file! = ":" && $file! = "Thumbs.db")                 {
   
    echo ' <a target= "_blank" href= "'. $dir. $file. '" > '. $file. ' </a><br> '. ' \ n ";                 }             }             Closedir ($handle);         }     
   
6. PHP Destroy Directory

Deletes a directory, including its contents.

/***** * @dir-directory to destroy * @virtual [optional]-whether a virtual Directory * * Function Destroydir ($dir, $virtual = False) {     $ds = directory_separator;     $dir = $virtual? Realpath ($dir): $dir;     $dir = substr ($dir,-1) = = $ds? substr ($dir, 0,-1): $dir;     if (Is_dir ($dir) && $handle = Opendir ($dir))     {while         ($file = Readdir ($handle))         {             if ($file = =). ' | | $file = = ' ... ')             {                 continue;             }             ElseIf (Is_dir ($dir. $ds. $file))             {                 destroydir ($dir. $ds. $file);             }             else             {                 unlink ($dir. $ds. $file);             }         }         Closedir ($handle);         RmDir ($dir);         return true;     }     else     {         return false;     
7. PHP Parsing JSON data

Like most popular Web services such as Twitter, which provides data through an open API, it is always able to know how to parse the various delivery formats for API data, including Json,xml, and so on.

8. PHP Parsing XML data

XML string $xml _string= "<?xml version= ' 1.0 '?> <users> <user id= ' 398 ' > <name>foo</name > <email>[email protected]</name> </user> <user id= ' 867 ' > <name>Foobar</name> <email>[email protected]</name> </user> </users> ";   Load the XML string using simplexml $xml = simplexml_load_string ($xml _string);   
9. PHP Create a log thumbnail name

Create a user-friendly log thumbnail name.

function Create_slug ($string) {$slug =preg_replace ('/[^a-za-z0-9-]+/', '-', $string); return $slug;}
PHP Gets the client real IP address

The function will get the real IP address of the user, even if he uses a proxy server.

function getrealipaddr () {     if (!emptyempty ($_server[' http_client_ip '))     {         $ip =$_server[' Http_client_ IP '];     }     ElseIf (!emptyempty ($_server[' http_x_forwarded_for '))     //to Check IP is pass from proxy     {         $ip =$_server[' Http_x_forwarded_for '];     }     else     {         $ip =$_server[' remote_addr ');     }     
PHP Mandatory File Download

To provide users with mandatory file download function.

PHP Create Tag Cloud

function Getcloud ($data = Array (), $minFontSize = n, $maxFontSize =) {$minimumCount = min (array_values ($data)); $maximumCount = Max (Array_values ($data)); $spread = $maximumCount-$minimumCount; $cloudHTML = ";   $cloudTags = Array ();   $spread = = 0 && $spread = 1; foreach ($data as $tag = + $count) {$size = $minFontSize + ($count-$minimumCount) * ($maxFontSize-$minFontSize )/$spread; $cloudTags [] = ' <a style= ' font-size: '. Floor ($size). ' px '. ' "href=" # "title=" \ ". $tag. ' \ ' returned a count of '. $count. ' > '. Htmlspecialchars (Stripslashes ($tag)). ' </a> '; } return join ("\ n", $cloudTags). "\ n";  }/************************** * * * * usage ***/$arr = array (' Actionscript ' = +, ' Adobe ' = ', ' array ' = The ' Background ' +, ' Blur ' +, ' Canvas ', ' + ', ' Class ', ' + ', ' Color Palette ' and ' all ', ' Crop ' = 4 2, ' Delimiter ' +, ' Depth ' and ' + ', ' Design ' and ' 8, ' Encode ', ' EnCryption ' = ' and ' Extract ', ' Filters ' and ' 42 ';  Echo Getcloud ($arr, 12, 36);
PHP looks for the similarity of two strings

PHP provides a minimal use of the Similar_text function, but this function is useful for comparing two strings and returning percentages of similar degrees.

PHP uses the Gravatar generic avatar in the application

With WordPress becoming more and more popular, Gravatar is also popular with them. Because Gravatar provides an easy-to-use API, it is also very convenient to incorporate it into your application.

PHP truncates text at character break points

The so-called hyphenation (word break), a place where a word can be broken when changing careers. This function truncates the string at the hyphenation point.

Original PHP Code by CHIRP Internet:www.chirp.com.au//Please acknowledge use of the this header for this code by including. function Mytruncate ($string, $limit, $break = ".", $pad = "...") {//return with no change if string is shorter than $limit I F (strlen ($string) <= $limit) return $string;   
Zip compression for PHP files
/* Creates a compressed zip file */function Create_zip ($files = Array (), $destination = ', $overwrite = False) {//if the  ZIP file already exists and overwrite is false, return False if (file_exists ($destination) &&! $overwrite) {return False }//vars $valid _files = Array (); If files were passed in ... if (Is_array ($files)) {//cycle through each file foreach ($files as $file) {//make sure the file exists if (File_exists ($fi Le) {$valid _files[] = $file;}} //if we have good files ... if (count ($valid _files)) {//create the archive $zip = new ziparchive (); if ($zip->open ($des Tination, $overwrite? Ziparchive::overwrite:ziparchive::create)!== true) {return false;}//add the files foreach ($valid _files as $file) {$ Zip->addfile ($file, $file);   }//debug//echo ' The zip archive contains ', $zip->numfiles, ' files with a status of ', $zip->status; Close the zip--done!   $zip->close (); Check to make sure the file exists return file_exists ($destination); } else { return false; }}/***** Example Usage ***/$files =array (' file1.jpg ', ' file2.jpg ', ' file3.gif ');  Create_zip ($files, ' Myzipfile.zip ', true);
PHP Extract Zip file
PHP default HTTP string for URL address

Sometimes you need to accept the URL input from some forms, but the user rarely adds the http://field, and this code adds the field to the URL.

if (!preg_match ("/^ (HTTP|FTP):/", $_post[' URL '))) {    
PHP converts URL strings to hyperlinks

This function converts the URL and e-mail address string into clickable hyperlinks.

function Makeclickablelinks ($text) {$text = Eregi_replace (' (((f|ht) {1}tp://) [[email protected]:%_+.~#?&//=]+] ', ' <a href= ' \1 ' >\1</a> ', $text); $text = Eregi_replace (' ([: Space:] () [{}]) (www.[ [Email protected]:%_+.~#?&//=]+] ', ' \1<a href= ' http://\2 ' >\2</a> ', $text); $text = Eregi_replace (' ([_.0-9a-z-][email protected] ([0-9a-z][0-9a-z-]+.) +[a-z]{2,3}) ', ' <a href= ' mailto:\1 ' >\1</a> ', $text);   
PHP Adjust image size

Creating an image thumbnail takes a lot of time, and this code will help you understand the logic of the thumbnail.

/********************** * @filename-path to the image * @tmpname-temporary path to thumbnail * @xmax-max width * @ymax- Max Height */function Resize_image ($filename, $tmpname, $xmax, $ymax) {     $ext = explode (".", $filename);     $ext = $ext [Count ($ext)-1];        if ($ext = = "JPG" | | $ext = = "jpeg")         $im = Imagecreatefromjpeg ($tmpname);     ElseIf ($ext = = "png")         $im = Imagecreatefrompng ($tmpname);     ElseIf ($ext = = "gif")         $im = Imagecreatefromgif ($tmpname);        $x = Imagesx ($im);     $y = Imagesy ($im);        if ($x <= $xmax && $y <= $ymax)         return $im;        if ($x >= $y) {         $newx = $xmax;         $newy = $newx * $y/$x;     }     else {         $newy = $ymax;         $NEWX = $x/$y * $newy;     }        $im 2 = Imagecreatetruecolor ($newx, $newy);     Imagecopyresized ($im 2, $im, 0, 0, 0, 0, Floor ($newx), Floor ($newy), $x, $y);     
PHP detects AJAX requests

Most JavaScript frameworks, such as Jquery,mootools, send additional Http_x_requested_with header information when making AJAX requests, so you can detect AJAX requests on the server side as they are an AJAX request.

if (!emptyempty ($_server[' Http_x_requested_with ')) && strtolower ($_server[' http_x_requested_with ']) = = ' XMLHttpRequest ') {     
22. Keyword highlighting
function Highlight ($sString, $aWords) {     if (!is_array ($aWords) | | emptyempty ($aWords) | |!is_string ($sString)) {
   return false;     }      $sWords = implode (' | ', $aWords);     
23. Get the users of your FeedBurner
function Get_average_readers ($feed _id, $interval = 7) {     $today = date (' y-m-d ', Strtotime ("Now");     $ago = Date (' y-m-d ', Strtotime ("-". $interval. "Days"));     $feed _url= "https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=". $feed _id. " &dates= ". $ago.", ". $today;     $ch = Curl_init ();     curl_setopt ($ch, Curlopt_returntransfer, 1);     curl_setopt ($ch, Curlopt_url, $feed _url);     $data = curl_exec ($ch);     Curl_close ($ch);     $xml = new SimpleXMLElement ($data);     $FB = $xml->feed->entry[' circulation ');      $NB = 0;     foreach ($xml->feed->children () as $circ) {         $NB + = $CIRC [' circulation '];     }      
24. Automatic password generation
function Generatepassword ($length =9, $strength =0) {     $vowels = ' Aeuy ';     $consonants = ' Bdghjmnpqrstvz ';     if ($strength >= 1) {         $consonants. = ' Bdghjlmnpqrstvwxz ';     }     if ($strength >= 2) {         $vowels. = "Aeuy";     }     if ($strength >= 4) {         $consonants. = ' 23456789 ';     }     if ($strength >= 8) {         $vowels. = ' @#$% ';     }      $password = ";     $alt = time ()% 2;     for ($i = 0; $i < $length; $i + +) {         if ($alt = = 1) {             $password. = $consonants [(rand ()% strlen ($consonants))];             $alt = 0;         } else {             $password. = $vowels [(rand ()% strlen ($vowels))];             $alt = 1;         }     }     
25. Compress multiple CSS files
Header (' content-type:text/css '); Ob_start ("compress"); function Compress ($buffer) {/   * Remove comments */   $buffer = Preg_replace ('!/\*[^*]*\*+ ([^/][^*]*\*+) */! ', ', $buffer);   /* Remove tabs, spaces, newlines, etc. *   /$buffer = str_replace (Array ("\ r \ n", "\ r", "\ n", "\ T", "  ', '",    ' 
    '), ', $buffer);   return $buffer; }/  * Your CSS files */include (' master.css '); include (' typography.css '); include (' grid.css '); include (' Print.css ') ; Include (' handheld.css ');  
26. Get a short URL
function Gettinyurl ($url) {     
27. Age based on birthdays
function Age ($date) {     $year _diff = ';     $time = Strtotime ($date);     if (FALSE = = = $time) {         return ';     }      $date = Date (' y-m-d ', $time);     List ($year, $month, $day) = Explode ("-", $date);     $year _diff = Date ("Y") – $year;     $month _diff = Date ("M") – $month;     $day _diff = Date ("D") – $day;     if ($day _diff < 0 | | $month _diff < 0) $year _diff–;      
28. Calculate Execution Time
Create a variable for start time $time _start = Microtime (true);  Place your php/html/javascript/css/etc. Here  //create a variable for end time $time _end = Microtime (true);//subtract the other times to get seconds $time = $t ime_end-$time _start;  
Maintenance Mode for PHP
function maintenance ($mode = FALSE) {     if ($mode) {         if (basename ($_server[' script_filename '])! = ' Maintenance.php ') {             header ("location:http://example.com/maintenance.php");             Exit;         }     } else{         if (basename ($_server[' script_filename ') = = = ' maintenance.php ') {             header ("location:http:// example.com/");             Exit;         }     
30. Block CSS styles from being cached
31. Increase ST\ND\RD for numbers, etc.
function make_ranked ($rank) {     $last = substr ($rank,-1);     $seclast = substr ($rank,-2,-1);     if ($last > 3 | | $last = = 0) $ext = ' th ';     else if ($last = = 3) $ext = ' rd ';     else if ($last = = 2) $ext = ' nd ';     else $ext = ' st ';       if ($last = = 1 && $seclast = = 1) $ext = ' th ';     if ($last = = 2 && $seclast = = 1) $ext = ' th ';     if ($last = = 3 && $seclast = = 1) $ext = ' th ';       

PHP some useful custom function collection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.