10 super useful PHP code snippets worth collecting _ PHP

Source: Internet
Author: User
This article mainly introduces 10 super useful PHP code snippets worth adding to your favorites, this article describes blacklist filtering, random color generator, download files from the Internet, force download files, and display users' Gravatar portraits by Email, if you need it, you can refer to PHP, which is often criticized, devalued, and joke. it turns out that PHP is the most popular programming language in website development around the world. The biggest disadvantage of PHP is that it is too simple, the syntax is not rigorous, and the framework system is weak. but this is also its biggest advantage. an ordinary person with a programming background only needs to study PHP for half a day, you can get started with developing web applications.

Some people on the Internet summarize the features of several programming languages, which I think makes sense:

The code is as follows:


PHP is: Quick and Dirty
Java is: Beauty and Slowly
Ruby is: Quick and Beauty
Python is Quick and Simple.

In the popularity of PHP, a lot of practical PHP code snippets have been summarized on the internet. these code snippets can be used when you encounter similar problems and pasted in the past, which is very efficient, it saves time and effort. Putting the excellent code summarized by these programmers into their own knowledge base is a good habit for learning programmers.

I. blacklist filtering

The code is as follows:


Function is_spam ($ text, $ file, $ split = ':', $ regex = false ){
$ Handle = fopen ($ file, 'RB ');
$ Contents = fread ($ handle, filesize ($ file ));
Fclose ($ handle );
$ Lines = explode ("n", $ contents );
$ Arr = array ();
Foreach ($ lines as $ line ){
List ($ word, $ count) = explode ($ split, $ line );
If ($ regex)
$ Arr [$ word] = $ count;
Else
$ Arr [preg_quote ($ word)] = $ count;
}
Preg_match_all ("~ ". Implode ('|', array_keys ($ arr ))."~ ", $ Text, $ matches );
$ Temp = array ();
Foreach ($ matches [0] as $ match ){
If (! In_array ($ match, $ temp )){
$ Temp [$ match] = $ temp [$ match] + 1;
If ($ temp [$ match] >=$ arr [$ word])
Return true;
}
}
Return false;
}

$ File = 'spam.txt ';
$ Str = 'This string has cat, dog word ';
If (is_spam ($ str, $ file ))
Echo 'this is spam ';
Else
Echo 'This is not spam ';
AB: 3
Dog: 3
Cat: 2
Monkey: 2


II. random color generator

The code is as follows:


Function randomColor (){
$ Str = '#';
For ($ I = 0; $ I <6; $ I ++ ){
$ RandNum = rand (0, 15 );
Switch ($ randNum ){
Case 10: $ randNum = 'a'; break;
Case 11: $ randNum = 'B'; break;
Case 12: $ randNum = 'C'; break;
Case 13: $ randNum = 'd'; break;
Case 14: $ randNum = 'e'; break;
Case 15: $ randNum = 'F'; break;
}
$ Str. = $ randNum;
}
Return $ str;
}
$ Color = randomColor ();


3. download files from the network

The code is as follows:


Set_time_limit (0 );
// Supports all file types
// URL Here:
$ Url = 'http: // somsite.com/some_video.flv ';
$ Pi = pathinfo ($ url );
$ Ext = $ pi ['extension'];
$ Name = $ pi ['filename'];

// Create a new cURL resource
$ Ch = curl_init ();

// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_HEADER, false );
Curl_setopt ($ ch, CURLOPT_BINARYTRANSFER, true );
Curl_setopt ($ ch, CURLOPT_AUTOREFERER, true );
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, true );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );

// Grab URL and pass it to the browser
$ Opt = curl_exec ($ ch );

// Close cURL resource, and free up system resources
Curl_close ($ ch );

$ SaveFile = $ name. '.'. $ ext;
If (preg_match ("/[^ 0-9a-z. _-]/I", $ saveFile ))
$ SaveFile = md5 (microtime (true). '.'. $ ext;

$ Handle = fopen ($ saveFile, 'wb ');
Fwrite ($ handle, $ opt );
Fclose ($ handle );
IV. Alexa/Google Page Rank

Function page_rank ($ page, $ type = 'Alexa '){
Switch ($ type ){
Case 'Alexa ':
$ Url = 'http: // alexa.com/siteinfo /';
$ Handle = fopen ($ url. $ page, 'r ');
Break;
Case 'Google ':
$ Url = 'http: // google.com/search? Client = navclient-auto & ch = 6-1484155081 & features = Rank & q = info :';
$ Handle = fopen ($ url. 'http: // '. $ page, 'r ');
Break;
}
$ Content = stream_get_contents ($ handle );
Fclose ($ handle );
$ Content = preg_replace ("~ (N | t | ss + )~ ",'', $ Content );
Switch ($ type ){
Case 'Alexa ':
If (preg_match ('~

(. + ?)

~ Im ', $ content, $ matches )){
Return $ matches [2];
} Else {
Return FALSE;
}
Break;
Case 'Google ':
$ Rank = explode (':', $ content );
If ($ rank [2]! = '')
Return $ rank [2];
Else
Return FALSE;
Break;
Default:
Return FALSE;
Break;
}
}
// Alexa Page Rank:
Echo 'Alexa Rank: '. page_rank ('techug. com ');
Echo'
';
// Google Page Rank
Echo 'Google Rank: '. page_rank ('techug. com', 'Google ');

5. Force File Download

The code is as follows:


$ Filename = $ _ GET ['file']; // Get the fileid from the URL
// Query the file ID
$ Query = sprintf ("SELECT * FROM tableName WHERE id = '% s'", mysql_real_escape_string ($ filename ));
$ SQL = mysql_query ($ query );
If (mysql_num_rows ($ SQL)> 0 ){
$ Row = mysql_fetch_array ($ SQL );
// Set some headers
Header ("Pragma: public ");
Header ("Expires: 0 ");
Header ("Cache-Control: must-revalidate, post-check = 0, pre-check = 0 ");
Header ("Content-Type: application/force-download ");
Header ("Content-Type: application/octet-stream ");
Header ("Content-Type: application/download ");
Header ("Content-Disposition: attachment; filename =". basename ($ row ['filename']). ";");
Header ("Content-Transfer-Encoding: binary ");
Header ("Content-Length:". filesize ($ row ['filename']);

@ Readfile ($ row ['filename']);
Exit (0 );
} Else {
Header ("Location :/");
Exit;
}


6. show your Gravatar Avatar by Email

The code is as follows:


$ Gravatar_link = 'http: // www.gravatar.com/avatar/'. md5 ($ comment_author_email ).'? S = 32 ';
Echo '';


7. obtain the number of RSS subscriptions through cURL

The code is as follows:


$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, 'https: // feedburner.google.com/api/awareness/1.0/GetFeedData? Id = 7qkrmib4r9rscbplq5qgadiiq4 ');
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, 2 );
$ Content = curl_exec ($ ch );
$ Subscribers = get_match ('/circulation = "(. *)"/isu', $ content );
Curl_close ($ ch );


VIII. time difference calculation functions

The code is as follows:


Function ago ($ time)
{
$ Periods = array ("second", "minute", "hour", "day", "week", "month", "year", "decade ");
$ Lengths = array ("60", "60", "24", "7", "4.35", "12", "10 ");

$ Now = time ();

$ Difference = $ now-$ time;
$ Tense = "ago ";

For ($ j = 0; $ difference >=$ lengths [$ j] & $ j <count ($ lengths)-1; $ j ++ ){
$ Difference/= $ lengths [$ j];
}

$ Difference = round ($ difference );

If ($ difference! = 1 ){
$ Periods [$ j]. = "s ";
}

Return "$ difference $ periods [$ j] 'ago '";
}


9. crop images

The code is as follows:


$ Filename = "test.jpg ";
List ($ w, $ h, $ type, $ attr) = getimagesize ($ filename );
$ Src_im = imagecreatefromjpeg ($ filename );

$ Src_x = '0'; // begin x
$ Src_y = '0'; // begin y
$ Src_w = '000000'; // width
$ Src_h = '000000'; // height
$ Dst_x = '0'; // destination x
$ Dst_y = '0'; // destination y

$ Dst_im = imagecreatetruecolor ($ src_w, $ src_h );
$ White = imagecolorallocate ($ dst_im, 255,255,255 );
Imagefill ($ dst_im, 0, 0, $ white );

Imagecopy ($ dst_im, $ src_im, $ dst_x, $ dst_y, $ src_x, $ src_y, $ src_w, $ src_h );

Header ("Content-type: image/png ");
Imagepng ($ dst_im );
Imagedestroy ($ dst_im );


10. check whether the website is down

The code is as follows:


Function Visit ($ url ){
$ Agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"; $ ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_USERAGENT, $ agent );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_VERBOSE, false );
Curl_setopt ($ ch, CURLOPT_TIMEOUT, 5 );
Curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, FALSE );
Curl_setopt ($ ch, CURLOPT_SSLVERSION, 3 );
Curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, FALSE );
$ Page = curl_exec ($ ch );
// Echo curl_error ($ ch );
$ Httpcode = curl_getinfo ($ ch, CURLINFO_HTTP_CODE );
Curl_close ($ ch );
If ($ httpcode> = 200 & $ httpcode <300) return true;
Else return false;
}
If (Visit ("http://www.google.com "))
Echo "Website OK". "n ";
Else
Echo "Website DOWN ";

Related Article

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.