PHP Utility Code

Source: Internet
Author: User
1. PHP can read a random string 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)];} return $password; } 2. PHP generates a random string if you don't 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 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmn opqrstuvwxyz0123456789 "; Srand (Double) microtime () *1000000); for ($i =0; $i < $l; $i + +) {$rand. = $c [Rand ()%strlen ($c)];} return $rand; } 3. PHP encoded e-mail address using this code, you can encode any e-mail address as an HTML character entity to prevent it from being collected by the spam program. function Encode_email ($email = ' info@domain.com ', $linkText = ' contact Us ', $attrs = ' class= ' Emailencoder "') {//Remplazar 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 = "; $part 4 = "; $encoded = "; return $encoded; } 4. PHP Verification Email Address Email Verification is probably the most common form validation in Web Forms, in addition to verifying e-mail addresses, you can also choose to check 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}) [Wind_phpcode_0]quot;, $email)) if ($test _mx) {list ($username, $domain) = Split ("@", $email); return GETMXRR ($ domain, $mxrecords); } else return true; else return false; } 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 '. $file. '
'." \ n "; }} closedir ($handle); }}} 6. The 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 ($d IR, 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 as with 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 of API data, including Json,xml, and so on. $json _string= ' {"id": 1, "name": "foo", "email": "foo@foobar.com", "Interest": ["WordPress", "PHP"]} '; $obj =json_decode ($json _string); Echo $obj->name; Prints foo echo $obj->interest[1]; Prints PHP 8. PHP parses XML data//xml string $xml _string= " Foo foo@bar.com Foobar foobar@foo.com "; Load the XML string using simplexml $xml = simplexml_load_string ($xml _string); Loop through the each node of user foreach ($xml->user as $user) {//access attribute echo $user [' id '], ';//subnod ES is accessed by-operator Echo $user->name, "; echo $user->email, '
'; } 9. PHP creates a user-friendly log thumbnail name by creating a log thumbnail name. function Create_slug ($string) {$slug =preg_replace ('/[^a-za-z0-9-]+/', '-', $string); return $slug;} PHP get the real IP address of the client this 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 ');} return $ip; } 11. PHP mandatory file download to provide users with mandatory file download function. /******************** * @file-path to File * * function Force_download ($file) {if (Isset ($file)) && (File_exists ( $file)) {header ("Content-length:". FileSize ($file)); Header (' Content-type:application/octet-stream '); Header (' content-disposition:attachment; Filename= '. $file. '"'); ReadFile ("$file"); } else {echo "No file selected";}} PHP Create Tag Cloud function Getcloud ($data = Array (), $minFontSize = A, $maxFontSize =) {$minimumCount = min (array_value S ($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 [] = '. Htmlspecialchars (Stripslashes ($tag)). ''; } 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 ' 28 ', ' Design ' = 8, ' Encode ', ' and ' encryption ', ' Extract ', ' Filters ' = 42); Echo Getcloud ($arr, 12, 36); PHP search for two strings of similarity PHP provides a minimal use of the Similar_text function, but this function is useful for comparing two strings and returning a percentage similar to the other. Similar_text ($string 1, $string 2, $percent); $percent would have the percentage of similarity 14. PhP use Gravatar generic avatar in the application with the popularity of WordPress, Gravatar also become popular. Because Gravatar provides an easy-to-use API, it is also very convenient to incorporate it into your application. /****************** * @email-email address to show Gravatar for * @size-size of Gravatar * @default-url of default Grav ATAR to use * @rating-rating of Gravatar (G, PG, R, X) */function Show_gravatar ($email, $size, $default, $rating) {echo ''; } 15. PHP truncates text at character breakpoints so-called hyphenation (word break), where a word can be broken in a career change. 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; is $break present between $limit and the end of the string? if (false!== ($breakpoint = Strpos ($string, $break, $limit))) {if ($breakpoint < strlen ($string)-1) {$string = subst R ($string, 0, $breakpoint). $pad; }} return $string; }/***** Example ****/$short _string=mytruncate ($long_string, 100, "); PHP file Zip compression/* Creates a compressed zip file */function Create_zip ($files = Array (), $destination = ', $overwrite = f Alse) {//if The zip file already exists and overwrite is false, return False if (file_exists ($destination) &&! $ov Erwrite) {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 files/********************** * @file-path to zip file * @destination-destination directory for unzipped fil ES */function Unzip_file ($file, $destination) {//create object $zip = new Ziparchive ();//Open Archive if ($zip->op En ($file)!== TRUE) {die (' Could not open Archive '),}//extract contents to destination directory $zip->extractto ($d Estination); Close archive $zip->close (); Echo ' Archive extracted to directory '; } 18. PHP preset http strings for URL addresses sometimes need to accept some form of URL input, but users rarely add http://field, this code will add the field for the URL. if (!preg_match ("/^ (HTTP|FTP):/", $_post[' URL '))) {$_post[' url '] = ' http://'. $_post[' URL '];} PHP convert URL string to hyperlink This function converts the URL and e-mail address string to a clickable hyperlink. function Makeclickablelinks ($text) {$text = Eregi_replace (' (((f|ht) {1}tp://) [-a-za-z0-9@:%_+.~#?&//=]+] ', ' \1 ', $text); $text = Eregi_Replace (' ([: Space:] () [{}]) (www.[ -a-za-z0-9@:%_+.~#?&//=]+) ', ' \1\2 ', $text); $text = Eregi_replace (' ([_.0-9a-z-]+@ ([0-9a-z][0-9a-z-]+.)] +[a-z]{2,3}) ', ' \1 ', $text); return $text;} PHP resizing image size It takes a lot of time to create an image thumbnail, 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 [Coun T ($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 = Imagec Reatetruecolor ($newx, $newy); Imagecopyresized ($im 2, $im, 0, 0, 0, 0, Floor ($newx), Floor ($newy), $x, $y); ReTurn $im 2; } 21. PHP detects AJAX requests most of the JavaScript frameworks such as jquery,mootools, etc., when making an AJAX request, will send additional Http_x_requested_with header information, head when they an AJAX request, so you can in the service The AJAX request is detected by the device side. if (!emptyempty ($_server[' Http_x_requested_with ')) && strtolower ($_server[' http_x_requested_with ']) = = ' XMLHttpRequest ') {//if AJAX Request then}else{//something Else}
  • 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.