Share 21 PHP function code snippets that you often use
The following is, in PHP development, often used in the 21 function code snippets, when we use, it can be used directly.
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.
/**************
[Email protected]–length of random string (must be a multiple of 2)
**************/
function readable_random_string ($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 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.
/************* ?
[Email protected]–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)];?
?? ?} ?
?? "Return"? $rand;?
}
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 ') {?
?? ?//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 2? = ' Ilto: ';?
??? ? $part 3? = ' "'. $attrs. ' > ';?
?? ? $part 4? = ''; ?
?? ? $encoded? = ''; ?
?? "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{?
?? ??? ? return? False
?? ?}
}
5. PHP Lists directory contents
function? List_files ($dir) {?
?? ? if (Is_dir ($dir)) {?
?? ??? ??? ? if ($handle? = Opendir ($dir)) {?
?? ??? ??? ??? ? while ($file = Readdir ($handle))!== false) {?
?? ??? ??? ??? ??? The IF ($file!! = "." &&? $file?! = ":" &&? $file?! = "Thumbs.db") {
?? ??? ??? ??? ??? "Echo". $file. '
'." \ n ";?
?? ??? ??? ??? ?} ?
?? ??? ??? ??? ?} ?
?? ??? ??? ? Closedir ($handle);?
?? ??? ??? ?} ?
?? ??? ?} ?
?}
6. PHP Destroy Directory
Deletes a directory, including its contents.
/***** ?
[Email protected]–directory to destroy?
[Email protected] [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.
$json _string = ' {"id": 1, "name": "foo", "email": "[email protected]", "interest": ["WordPress", "PHP"]} ';?
$obj =json_decode ($json _string);?
Echo?? $obj->name;? Prints foo?
Echo?? $obj->interest[1];? Prints php?
8. PHP Parsing XML data
XML string?
$xml _string = " ?
?
?
Foo ?
[Email protected]?
?
?
Foobar ?
[Email protected]?
?
"; ?
Load the XML string using SimpleXML?
$xml? = simplexml_load_string ($xml _string);?
Loop through the each node of the user?
Foreach? ($xml->user??? $user)?
{ ?
Access attribute?
Echo?? $user [' id '], ';?
Subnodes is accessed by, operator?
Echo?? $user->name, ';?
Echo?? $user->email, '
’; ?
}
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 '];?
?? ?}
?? ?//to Check IP? Is it?? Pass?? From? Proxy
?? ? ElseIf (!emptyempty ($_server[' http_x_forwarded_for ')) {?
?? ??? ? $ip =$_server[' http_x_forwarded_for ';
?? ?}
?? ? Else {
?? ??? ? $ip =$_server[' remote_addr '];?
?? ??? ?}
?? ? return? $ip;?
}
PHP Mandatory File Download
To provide users with mandatory file download function.
/******************** ?
[Email protected]–path to file?]
*/ ?
function Force_download ($file) {?
?? ? if ((Isset ($file)) && (File_exists ($file))) {?
?? ??? Header (' Content-length: '. FileSize ($file));?
?? ??? ? header (' Content-type:application/octet-stream ');?
?? ??? The header (' content-disposition:attachment; Filename= '. $file. ' " '); ?
?? ??? ? ReadFile ($file);
?? ?} Else{?
?? ??? ? echo ' No file selected ';?
?? ??? ?} ?
}
PHP Create Tag Cloud
function? Getcloud ($data =array (), $minFontSize =12, $maxFontSize =30) {?
?? ? $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 []= '. Htmlspecialchars (stripslashes
($tag)). "; ?
??????? }
??????? Return? Join ("\ n", $cloudTags). " \ n ";?
} ?
/************************** ?
Sample usage ***/?
$arr =array (' actionscrip ' + +, ' Adobe ' + ' Array ', ' Background ' +, ' Blur ' + +, ' Canvas ' = 33 , ' Class ' and ' + ', ' Color Palette ' and ' all ', ' Crop ', ' Delimiter ', ' Depth ' and ' = '
, ' Design ' = 8, ' Encode ', ' and ' encryption ', ' and ' Extract ', ' Filters ' =>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.
Similar_text ($string 1,? $string 2,? $percent);?
$percent would have the percentage of similarity?
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.
/****************** ?
[Email protected]–email address to show Gravatar for?
[Email protected]–size of Gravatar?
[Email Protected]–url of default Gravatar to use?]
[Email protected]–rating of Gravatar (G, PG, R, X)?
*/ ?
function Show_gravatar ($email,? $size,? $default,? $rating) {?
?? "Echo"? '
Height= "'. $size. ' px '/> ';?
}
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 Code by including the this header. ?
function? Mytruncate ($string,? $limit,? $break = '. ',? $pad = ' ... ') {?
?? ?//return with no change if string is shorter than $limit?
??????? if (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? ?? ??? ??? ? $string? =? substr ($string, 0,? $breakpoint).? $pad;?
?????? ??? ?} ?
??????? } ?
??????? Return?? $string;?
} ?
/***** Example ****/?
$short _string =mytruncate ($long _string, 100, ");
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???? $file) {?
?????? ??? ??? ?//make sure the file exists?
?????? ??? ??? ? if (file_exists ($file)) {?
?????? ??? ??? ??? ? $valid _files [] =? $file;?
?????? ??? ??? ?} ?
?????? ??? ?} ?
??????? } ?
??????? If we have good files ...?
??????? if (count ($valid _files)) {?
?????? ??? ?//create the archive?
?????? ??? ? $zip? =? New? Ziparchive ();?
?????? ??? ? if ($zip->open ($destination, $overwrite?? Ziparchive::overwrite:ziparchive::create)!== true) {?
?????? ??? ??? ? return? false;?
?????? ??? ?} ?
?????? ??? ?//add the files?
?????? ??? ? foreach ($valid _files???? $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
/********************** ?
[Email protected]–path to zip file?]
[Email protected]–destination directory for unzipped files?
*/ ?
function? Unzip_file ($file,? $destination) {?
?? ?//Create object?
?? ? $zip? =? New? Ziparchive ();?
?? ?//Open archive?
?? ? If? ($zip->open ($file)!== TRUE) { ?
?? ??? Die? (' Could not open archive ');?
?? ?} ?
?? ?//Extract contents to destination directory?
?? ? $zip->extractto ($destination);?
?? ?//Close archive?
?? ? $zip->close ();?
?? ? Echo ' Archive extracted to directory ';?
}
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 ')))) {?
?? ? $_post[' url '] = ' http://'. $_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://) [-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 Adjust image size
Creating an image thumbnail takes a lot of time, and this code will help you understand the logic of the thumbnail.
/********************** ?
[Email protected]–path to the image?
[Email protected]–temporary path to thumbnail?
[Email protected]–max width?]
[Email protected]–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);?
?? "Return"? $im 2;?
}
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 ') {?
?? ?//if AJAX Request then?
} else {
?? ?//something else?
} ?
Here, the 21 frequently used PHP function code snippet, the introduction is finished. Hope to be of help to you.