PHP is currently the most widely used web-based programming language, driving millions of web sites, including some large sites such as Facebook. This collection of 21 practical and convenient snippets of PHP code is helpful for each type of PHP developer.
1. PHP can read random string
This code creates a readable string that is closer to the word in the dictionary, and is practical and has a password validation feature.
/************** * @length-length of random string (must 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 don't need a readable string, use this function instead to create a random string that acts as a random password for the user.
/************* *@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)]; } return $rand; } |
3. PHP Encoded Email address
With this code, you can encode any e-mail address as an HTML character entity to prevent it from being collected by the Junk Mail 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 = ' <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 Authentication Email Address
E-mail authentication is perhaps the most common form of Web page verification, which, in addition to verifying e-mail addresses, optionally checks the MX record in the DNS of the mail domain to make the message validation 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)
{
if ($file!= "." && $file!= "..." && $file!= "Thumbs.db")
{
Echo ' <a target= ' _blank ' href= '. $dir. $file. ' " > '. $file. ' </a><br> '. ' \ n ";
}
}
Closedir ($handle);
}
}
} |
6. PHP Destruction 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
As with most popular WEB services such as Twitter, which provides data through an open API, it always knows how to parse the various delivery formats for 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 Parsing XML data
XML string $xml _string= "<?xml version= ' 1.0 '?> <users> <user id= ' 398 ' > <name>Foo</name> <email>foo@bar.com</name> </user> <user id= ' 867 ' > <name>Foobar</name> <email>foobar@foo.com</name> </user> </users> ";
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 '], '; Subnodes are accessed by-> operator echo $user->name, '; echo $user->email, ' <br/> '; } |
9. PHP Create log abbreviated name
Creates a user-friendly log thumbnail name.
function Create_slug ($string) { $slug =preg_replace ('/[^a-za-z0-9-]+/', '-', $string); return $slug; } |
PHP gets the client's real IP address
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 be pass from proxy { $ip =$_server[' http_x_forwarded_for ']; } Else { $ip =$_server[' remote_addr ']; } return $IP; } |
PHP Mandatory File Download
To provide users with mandatory file download capabilities.
/******************** * @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 = $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 [] = ' <a style= ' font-size: '. Floor ($size). ' PX '
. "Href=" # "title=". $tag.
' \ returned a count of '. $count. ' > '
. Htmlspecialchars (Stripslashes ($tag)). ' </a> ';
}
return join ("\ n", $cloudTags). "\ n";
}
/**************************
Sample usage ***/
$arr = Array (' Actionscript ' =>, ' Adobe ' =>, ' Array ' =>, ' Background ' => 43,
' Blur ' =>, ' Canvas ' =>, ' Class ' =>, ' Color Palette ' =>, ' crop ' => 42,
' Delimiter ' =>, ' Depth ' =>, ' design ' => 8, ' Encode ' =>, ' encryption ' => 30,
' Extract ' =>, ' Filters ' => 42);
Echo Getcloud ($arr, 12, 36); |
PHP looking for similarity of two strings
PHP provides a similar_text function that is rarely used, but this function is useful for comparing two strings and returning a percentage of similarity.
Similar_text ($string 1, $string 2, $percent); $percent would have the percentage of similarity |
PHP uses Gravatar generic avatar in applications
As WordPress becomes more and more popular, Gravatar is also popular. Because Gravatar provides an easy-to-use API, it is also easy to incorporate into applications.
/****************** * @email-email Address Gravatar * @size-size of Gravatar * @default-url of default Gravatar to use * @rating-rating of Gravatar (G, PG, R, X) */ function Show_gravatar ($email, $size, $default, $rating) { Echo ' ' &default= '. $default. ' &size= '. $size. ' &rating= '. $rating. ' width= '. $size. ' px ' Height= "'. $size. ' px '/> '; } |
PHP truncates text at character breakpoints
Hyphenation (word break), where a word can be disconnected during a career change. This function truncates the string at the hyphenation point.
Original PHP Code by CHIRP Internet:www.chirp.com.au Please acknowledge the use of this code by the including this header. function Mytruncate ($string, $limit, $break = ".", $pad = "...") { Return with no change if string is shorter than $limit if (strlen ($string) <= $limit) return $string;
are $break present between $limit and the end of the string? if (false!== ($breakpoint = Strpos ($string, $break, $limit)) { if ($breakpoint < strlen ($string)-1) { $string = substr ($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 = 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 ($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 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 uncompressed Zip file
/********************** * @file-path to zip file * @destination-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 for URL address preset HTTP string
Sometimes you need to accept URL input from some forms, but users rarely add http://fields, 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 to a clickable hyperlink.
function makeClickableLinks($text) { $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', '<a href="\1">\1</a>', $text); $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', '\1<a href="http://\2">\2</a>', $text); $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
return $text; }
|
Adjust image size in PHP
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);
return $im 2;
} |
PHP detects AJAX requests
Most JavaScript frameworks, such as Jquery,mootools, send an extra http_x_requested_with header message when an AJAX request is made, and the header is an AJAX request, so you can detect AJAX requests on the server side.
if (!emptyempty ($_server[' Http_x_requested_with ')) && strtolower ($_server[' http_x_requested_with ']) = = ' XMLHttpRequest ') { If AJAX Request Then }else{ Something else } |
English manuscript:Really Useful & Handy PHP Code Snippets | Web Developer Plus
Translation finishing:21+ practical and convenient PHP code excerpt | Mango