1. PHP readable random string this code creates a readable string that is closer to the word in the dictionary and is useful and has the password verification function. /************** @ Length & amp; ndash; lengthofrandomstring (mustbeamultipleof2) *... "> <LINKhref =" ht
1. PHP can read random strings
This code creates a readable string that is closer to a word in the dictionary and is practical and password-verified.
/**************
* @ 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. PHP generates a random string
If you do not need readable strings, use this function instead to create a random string as your random password.
/*************
* @ 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
This code can be used to encode any email address as an html character entity to prevent being collected by spam programs.
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 = '$ part2 = 'ilto :';
$ Part3 = '"'. $ attrs. '> ';
$ Part4 = '';
$ Encoded = '';
Return $ encoded;
}
4. PHP verification 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.
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 listing directory content
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. PHP destroy Directory
Delete 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. parse JSON data in PHP
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.
$ 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'], '';
// Subnodes are accessed by-> operator
Echo $ user-> name ,'';
Echo $ user-> email ,'
';
}
9. name scaling of PHP creation logs
Create a user-friendly log scaling name.
Function create_slug ($ string ){
$ Slug = preg_replace ('/[^ A-Za-z0-9-] +/', '-', $ string );
Return $ slug;
}
10. PHP obtains 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.
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
It provides users with mandatory file download functions.
/********************
* @ 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 cloud in PHP
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 [] = '.' "href =" # "title =" \ ". $ tag.
'\ 'Returned a count of'. $ count. '">'
. Htmlspecialchars (stripslashes ($ tag )).'';
}
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 in PHP
PHP provides a rarely used similar_text function, but this function is very useful for comparing two strings and returning a percentage of similarity.
Similar_text ($ string1, $ string2, $ percent );
// $ Percent will have the percentage of similarity
14. use the Gravatar profile picture in PHP applications
As WordPress becomes increasingly popular, Gravatar also becomes popular. Gravatar provides easy-to-use APIs, making it easy to include them in applications.
/******************
* @ 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. PHP truncates 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.
// Original PHP code by chiririnternet: 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. Zip compression of 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 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, $ 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 file in PHP.
/**********************
* @ 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. PHP presets the http string for the URL address
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.
If (! Preg_match ("/^ (http | ftp):/", $ _ POST ['URL']) {
$ _ POST ['URL'] = 'http: // '. $ _ POST ['URL'];
}
19. PHP converts the URL string into a hyperlink
This function converts the URL and e-mail address strings into clickable superlinks.
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;
}
20. PHP adjusted Image size
Creating image thumbnails takes a long time. This code helps you understand the thumbnails logic.
/**********************
* @ 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. PHP detects 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.
If (! Emptyempty ($ _ SERVER ['http _ X_REQUESTED_WITH ']) & strtolower ($ _ SERVER ['http _ X_REQUESTED_WITH']) = 'xmlhttprequest '){
// If AJAX Request Then
} Else {
// Something else
}