1. Reading random strings
ThisCodeA readable string is created to bring it closer to the word in the dictionary, which is practical and has the password verification function.Copy codeThe Code is as follows :/**************
* @ Length-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. Generate a random string
If you do not need readable strings, use this function instead to create a random string as your random password.Copy codeThe Code is as follows :/*************
* @ 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. encode the email address
This code can be used to encode any email address as an HTML character entity to prevent spamProgramCollection.Copy codeThe Code is as follows: 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 );
$ Part1 = '<a href = "ma ';
$ Part2 = 'ilto :';
$ Part3 = '"'. $ attrs. '> ';
$ Part4 = '</a> ';
$ Encoded = '<SCRIPT type = "text/JavaScript"> ';
$ Encoded. = "document. Write ('$ Part1 ');";
$ Encoded. = "document. Write ('$ Part2 ');";
Foreach ($ email as $ E)
{
$ Encoded. = "document. Write ('$ e ');";
}
$ Encoded. = "document. Write ('$ Part3 ');";
Foreach ($ linktext as $ L)
{
$ Encoded. = "document. Write ('$ l ');";
}
$ Encoded. = "document. Write ('$ part4 ');";
$ Encoded. = '</SCRIPT> ';
Return $ encoded;
}
4. Verify the email address
Email verification may be the most common web form verification. In addition to verifying the email address, this code can also choose to check MX records in the DNS to which the email domain belongs, making email verification more powerful.Copy codeThe Code is as follows: 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. List Directory contentCopy codeThe Code is as follows: 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. Destroy the Directory
Delete a directory, including its contents.Copy codeThe Code is as follows :/*****
* @ 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. parse JSON data
Like most popular Web services, such as Twitter, which provides data through open APIs, it always knows how to parse various transfer formats of API data, including JSON and XML.Copy codeThe Code is as follows: $ 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. parse XML dataCopy codeThe Code is as follows: // XML string
$ Xml_string = "<? XML version = '1. 0'?>
<Users>
<User id = '000000'>
<Name> Foo </Name>
<Email> foo@bar.com </Name>
</User>
<User id = '000000'>
<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. Create a log scaling name
Create a user-friendly log scaling name.Copy codeThe Code is as follows: function create_slug ($ string ){
$ Slug = preg_replace ('/[^ A-Za-z0-9-] +/', '-', $ string );
Return $ slug;
}
10. Obtain the real IP address of the client
This function will obtain the real IP address of the user, even if he uses the proxy server.Copy codeThe Code is as follows: 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. Mandatory File Download
It provides users with mandatory File Download functions.Copy codeThe Code is as follows :/********************
* @ 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 ";
}
}
12. Create a tag cloudCopy codeThe Code is as follows: 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 [] = '<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 '=> 35, 'adobe' => 22, 'array' => 44, 'background' => 43,
'Blur' => 18, 'canvas '=> 33, 'class' => 15, 'color paster' => 11, 'crop' => 42,
'Delimiter' => 13, 'dest' => 34, 'design' => 8, 'encode' => 12, 'encryption' => 30,
'Effect' => 28, 'filters '=> 42 );
Echo getcloud ($ arr, 12, 36 );
13. Search for similarity between two strings
PHP provides a rarely used similar_text function, but this function is very useful for comparing two strings and returning a percentage of similarity.Copy codeThe Code is as follows: similar_text ($ string1, $ string2, $ percent );
// $ Percent will have the percentage of Similarity
14. Use the gravatar universal profile picture in the Application
As WordPress becomes increasingly popular, gravatar also becomes popular. Gravatar provides easy-to-use APIs, making it easy to include them in applications.Copy codeThe Code is as follows :/******************
* @ Email-email address to show 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"/> ';
}
15. truncate text at the character breakpoint
Word break refers to the place where a word can be broken when it is switched. This function truncates the string at the break.Copy codeThe Code is as follows: // original PHP code by chirinternet: www.chirp.com. au
// Please acknowledge use of this Code by 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;
// Is $ 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 ,'');
16. File zip Compression Copy code The Code is as follows:/* 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 ins INS, $ 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 ***/
Optional files=array('file1.jpg ', 'file2.jpg', 'file3.gif ');
Create_zip ($ files, 'myzipfile.zip ', true );
17. decompress the ZIP fileCopy codeThe Code is as follows :/**********************
* @ 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-> extrac.pdf ($ destination );
// Close Archive
$ Zip-> close ();
Echo 'archive extracted to directory ';
}
18. preset an HTTP string for the URL
Sometimes you need to accept URL input in some forms, but few users add http: // fields. This code will add this field to the URL.Copy codeThe Code is as follows: if (! Preg_match ("/^ (HTTP | FTP):/", $ _ post ['url']) {
$ _ Post ['url'] = 'HTTP: // '. $ _ post ['url'];
}
19. Convert the URL string into a hyperlink
This function converts the URL and e-mail address strings into clickable superlinks.Copy codeThe Code is as follows: 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 })',
'<A href = "mailto: \ 1"> \ 1 </a>', $ text );
Return $ text;
}
20. Adjust the image size
Creating image thumbnails takes a long time. This Code helps you understand the thumbnails logic.Copy codeThe Code is as follows :/**********************
* @ 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;
}
$ IM2 = imagecreatetruecolor ($ newx, $ newy );
Imagecopyresized ($ IM2, $ im, 0, 0, 0, 0, floor ($ newx), floor ($ newy), $ X, $ y );
Return $ IM2;
}
21. Detect Ajax requests
Most JavaScript frameworks, such as jquery and mootools, send additional http_x_requested_with header information when sending Ajax requests. The header is an Ajax request, therefore, you can detect Ajax requests on the server side.Copy codeThe Code is as follows: if (! Emptyempty ($ _ server ['HTTP _ x_requested_with ']) & strtolower ($ _ server ['HTTP _ x_requested_with']) = 'xmlhttprequest '){
// If Ajax request then
} Else {
// Something else
}