Although PHP comes with a powerful library of functions, in many cases, we also have to write our own custom functions to implement certain functions and requirements. Here are some useful custom functions to solve some common needs, such as converting URL strings to hyperlinks, listing contents, verifying email addresses, etc.
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.
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.
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 = ' info@domain.com ', $linkText = ' contact Us ', $attrs = ' class= ' Emailencoder "') {//Remplaza R 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 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 Destroy Directory
Deletes a directory, including its contents.
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": "foo@foobar.com", "Interest": ["WordPress", "PHP"]} '; $obj =json_decode ( $json _string); Echo $obj->name; Prints Fooecho $obj->interest[1]; Prints PHP
8. PHP Parsing XML data
XML string $xml _string= "<, 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 '], '; C4/>//subnodes is accessed by, operator Echo $user->name, "; echo $user->email, ' <, br/> '; }
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 '); } return $IP;}
PHP Mandatory File Download
To provide users with mandatory file download function.
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"; }}