PHP Practical Code Collection _php tutorial

Source: Internet
Author: User
Tags ziparchive
1. Can read random string

This code creates a readable string that is closer to the word in the dictionary, and is practical and has password validation capabilities.
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 a readable string, use this function instead to create a random string, as a random password for the user, and so on.
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. Encoded Email 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.
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);

$part 1 = ' $part 2 = ' Ilto: ';
$part 3 = ' "'. $attrs. ' > ';
$part 4 = ";

$encoded = ";

return $encoded;
}

4. Verify your 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.
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 Contents
Copy 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 '. $file. '
'." \ n ";
}
}
Closedir ($handle);
}
}
}

6. Destroying the Directory

Deletes 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. 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.
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. Parsing XML Data
Copy CodeThe code is as follows:
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 the user
foreach ($xml->user as $user)
{
Access attribute
echo $user [' id '], ';
Subnodes is accessed by, operator
echo $user->name, ";
echo $user->email, '
';
}

9. Create a log thumbnail name

Create a user-friendly log thumbnail name.
Copy CodeThe code is as follows:
function Create_slug ($string) {
$slug =preg_replace ('/[^a-za-z0-9-]+/', '-', $string);
return $slug;
}

10. Get the real IP address of the client

The function will get the real IP address of the user, even if he uses a 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 was pass from proxy
{
$ip =$_server[' http_x_forwarded_for '];
}
Else
{
$ip =$_server[' remote_addr '];
}
return $IP;
}

11. mandatory File Download

To provide users with mandatory file download function.
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 cloud
Copy CodeThe code is as follows:
function Getcloud ($data = Array (), $minFontSize = A, $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 ' = +, ' Adobe ' = ' + ', ' array ' = +, ' Background ' = 43,
' Blur ' +, ' Canvas ' = +, ' Class ' = ', ' Color Palette ' and ' 42 ', ' Crop ',
' Delimiter ' and ' Depth ', ' Design ' = 8, ' Encode ', ' + ', ' encryption ' and ' = 30,
' Extract ', ' Filters ' and ' 42 ';
Echo Getcloud ($arr, 12, 36);

13. Look 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.
Copy CodeThe code is as follows:
Similar_text ($string 1, $string 2, $percent);
$percent would have the percentage of similarity

14. Using the Gravatar universal 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.
Copy CodeThe code is as follows:
/******************
* @email-email address to show Gravatar for
* @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 a character breakpoint

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.
Copy CodeThe code is as follows:
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 < strlen ($string)-1) {
$string = substr ($string, 0, $breakpoint). $pad;
}
}
return $string;
}
/***** Example ****/
$short _string=mytruncate ($long _string, 100, ");

16. File Zip compression
Copy CodeThe 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 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);

17. Unzip the Zip file
Copy 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->extractto ($destination);
Close Archive
$zip->close ();
Echo ' Archive extracted to directory ';
}

18. Preset HTTP strings for URL addresses

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.
Copy CodeThe code is as follows:
if (!preg_match ("/^ (HTTP|FTP):/", $_post[' URL '))) {
$_post[' url '] = ' http://'. $_post[' url '];
}
19. Convert URL strings to hyperlinks

This function converts the URL and e-mail address string into clickable hyperlinks.
Copy CodeThe code is as follows:
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. Adjust Image size

Creating an image thumbnail takes a lot of time, and this code will help you understand the logic of the thumbnail.
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;
}

$im 2 = Imagecreatetruecolor ($newx, $newy);
Imagecopyresized ($im 2, $im, 0, 0, 0, 0, Floor ($newx), Floor ($newy), $x, $y);
return $im 2;
}

21. Detecting 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.
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
}

http://www.bkjia.com/PHPjc/321197.html www.bkjia.com true http://www.bkjia.com/PHPjc/321197.html techarticle 1. Can read random string This code creates a readable string that is closer to the word in the dictionary, and is practical and has password validation capabilities. Copy the code code as follows:/**** ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.