10 super-useful, must-have-collection PHP code details

Source: Internet
Author: User
Tags explode learn php knowledge base
As a normal programmer, several languages are very normal, I believe most programmers will write a few PHP programs, if it is a web programmer, PHP must be necessary, even if you do not use it to develop large-scale software projects, but also how much understanding of its syntax.

PHP is the most widely used programming language in web development in the world, although it is often criticized, degraded, and joked. PHP's biggest drawback is too simple, grammar is not rigorous, framework system is weak, but this is its biggest advantage, a bit of programming background of ordinary people, only need to learn PHP half a day, you can start to develop Web applications.

Some people on the Internet to summarize the characteristics of several programming languages, I think it is quite reasonable:

PHP is: Quick and Dirty
Java is: Beauty and slowly
Ruby is: Quick and Beauty
Python is: Quick
and simple

In the popular popularity of PHP, online summed up a lot of useful PHP code snippets, these snippets in when you encounter similar problems, paste the past can be used, very efficient, very time-saving. Putting the good code that these programmers have summed up in their own knowledge base is a good habit of learning programmers.

First, blacklist filter

function is_spam ($text, $file, $split = ': ', $regex = False) {$handle = fopen ($fi     Le, ' 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 was not spam '; 
Ab:3dog:3cat:2monkey:2

Second, random color generator

function Randomcolor () {     $str = ' # ';     for ($i = 0; $i < 6; $i + +) {         $randNum = rand (0);         Switch ($randNum) {case             ten: $randNum = ' A ';             Case one: $randNum = ' B '; break;             Case: $randNum = ' C '; break;             Case: $randNum = ' D '; break;             Case: $randNum = ' E '; break;             Case: $randNum = ' F '; break;         }         $str. = $randNum;     }     return $str; } $color = Randomcolor ();

Third, download files from the network

Set_time_limit (0); Supports all file types//urls 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&am             P;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 (' ~<p class= "data (down|up)" > (. +?) </             P>~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 ');

V. Mandatory download of files

$filename = $_get[' file ']; Get the Fileid from the URL//Query of the file id $query = sprintf ("select * from tableName WHERE ID = '%s '", mysql_real_e Scape_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 }

VI. Display the user's Gravatar avatar via email

$gravatar _link = ' http://www.gravatar.com/avatar/'. MD5 ($comment _author_email). '? s=32 ';  Echo '  ';

Seven, get RSS subscriptions via Curl

$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);

Eight, time difference calculation function

Function ago ($time) {   $periods = Array ("Second", "Minute", "Hour", "Day", "Week", "Month", "year", "decade");   $lengths = Array ("Ten", "" "," "", "7", "4.35", "N", "Max");   $now = time ();       $difference     = $now-$time;       $tense         = "ago";   for ($j = 0; $difference >= $lengths [$j] && $j < count ($lengths)-1; $j + +) {       $difference/= $lengths [$j];< c9/>}   $difference = round ($difference);   if ($difference! = 1) {       $periods [$j].= "S";   }   Return "$difference $periods [$j] ' ago ';}

Nine, cut the picture

$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 = ' 100 '; Width$src_h = ' 100 '; 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);

Ten, 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 ";

The above is 10 super useful, must collect PHP code detailed introduction of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.