10 common code samples in PHP development
Last Update:2016-02-15
Source: Internet
Author: User
10 common code samples in PHP Development blacklist filtering random color generator downloads files from the Internet I. blacklist filtering
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
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 internet
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
$ 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. use Email to display users' Gravator portraits
$ Gravatar_link = 'http: // www.gravatar.com/avatar/'. md5 ($ comment_author_email ).'? S = 32 ';
Echo '';
7. use cURL to obtain the number of RSS subscriptions
$ 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
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. screenshot
$ 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
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 ";