10个超级有用、必须收藏的PHP代码样例

汉王 PHP 2016年11月17日 收藏
  1. 一、黑名单过滤
  2.  
  3. function is_spam($text, $file, $split = ':', $regex = false){ 
  4.     $handle = fopen($file, 'rb'); 
  5.     $contents = fread($handle, filesize($file)); 
  6.     fclose($handle); 
  7.     $lines = explode("n", $contents); 
  8.     $arr = array(); 
  9.     foreach($lines as $line){ 
  10.         list($word, $count) = explode($split, $line); 
  11.         if($regex) 
  12.             $arr[$word] = $count; 
  13.         else 
  14.             $arr[preg_quote($word)] = $count; 
  15.     } 
  16.     preg_match_all("~".implode('|', array_keys($arr))."~", $text, $matches); 
  17.     $temp = array(); 
  18.     foreach($matches[0] as $match){ 
  19.         if(!in_array($match, $temp)){ 
  20.             $temp[$match] = $temp[$match] + 1; 
  21.             if($temp[$match] >= $arr[$word]) 
  22.                 return true; 
  23.         } 
  24.     } 
  25.     return false; 
  26. } 
  27.  
  28. $file = 'spam.txt'; 
  29. $str = 'This string has cat, dog word'; 
  30. if(is_spam($str, $file)) 
  31.     echo 'this is spam'; 
  32. else 
  33.     echo 'this is not spam';
  34. ab:3
  35. dog:3
  36. cat:2
  37. monkey:2
  38. 二、随机颜色生成器
  39.  
  40. function randomColor() { 
  41.     $str = '#'; 
  42.     for($i = 0 ; $i < 6 ; $i++) { 
  43.         $randNum = rand(0 , 15); 
  44.         switch ($randNum) { 
  45.             case 10: $randNum = 'A'; break; 
  46.             case 11: $randNum = 'B'; break; 
  47.             case 12: $randNum = 'C'; break; 
  48.             case 13: $randNum = 'D'; break; 
  49.             case 14: $randNum = 'E'; break; 
  50.             case 15: $randNum = 'F'; break; 
  51.         } 
  52.         $str .= $randNum; 
  53.     } 
  54.     return $str; 
  55. } 
  56. $color = randomColor();
  57. 三、从网络下载文件
  58.  
  59. set_time_limit(0); 
  60. // Supports all file types 
  61. // URL Here: 
  62. $url = 'http://somsite.com/some_video.flv'; 
  63. $pi = pathinfo($url); 
  64. $ext = $pi['extension']; 
  65. $name = $pi['filename']; 
  66.  
  67. // create a new cURL resource 
  68. $ch = curl_init(); 
  69.  
  70. // set URL and other appropriate options 
  71. curl_setopt($ch, CURLOPT_URL, $url); 
  72. curl_setopt($ch, CURLOPT_HEADER, false); 
  73. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
  74. curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
  75. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
  76. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
  77.  
  78. // grab URL and pass it to the browser 
  79. $opt = curl_exec($ch); 
  80.  
  81. // close cURL resource, and free up system resources 
  82. curl_close($ch); 
  83.  
  84. $saveFile = $name.'.'.$ext; 
  85. if(preg_match("/[^0-9a-z._-]/i", $saveFile)) 
  86.     $saveFile = md5(microtime(true)).'.'.$ext; 
  87.  
  88. $handle = fopen($saveFile, 'wb'); 
  89. fwrite($handle, $opt); 
  90. fclose($handle);
  91. 四、Alexa/Google Page Rank
  92.  
  93. function page_rank($page, $type = 'alexa'){ 
  94.     switch($type){ 
  95.         case 'alexa': 
  96.             $url = 'http://alexa.com/siteinfo/'; 
  97.             $handle = fopen($url.$page, 'r'); 
  98.         break; 
  99.         case 'google': 
  100.             $url = 'http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:'; 
  101.             $handle = fopen($url.'http://'.$page, 'r'); 
  102.         break; 
  103.     } 
  104.     $content = stream_get_contents($handle); 
  105.     fclose($handle); 
  106.     $content = preg_replace("~(n|t|ss+)~",'', $content); 
  107.     switch($type){ 
  108.         case 'alexa': 
  109.             if(preg_match('~<div class="data (down|up)"><img.+?>(.+?) </div>~im',$content,$matches)){ 
  110.                 return $matches[2]; 
  111.             }else{ 
  112.                 return FALSE; 
  113.             } 
  114.         break; 
  115.         case 'google': 
  116.             $rank = explode(':',$content); 
  117.             if($rank[2] != '') 
  118.                 return $rank[2]; 
  119.             else 
  120.                 return FALSE; 
  121.         break; 
  122.         default: 
  123.             return FALSE; 
  124.         break; 
  125.     } 
  126. } 
  127. // Alexa Page Rank: 
  128. echo 'Alexa Rank: '.page_rank('techug.com'); 
  129. echo '
  130. '; 
  131. // Google Page Rank 
  132. echo 'Google Rank: '.page_rank('techug.com', 'google');
  133. 五、强制下载文件
  134.  
  135. $filename = $_GET['file']; //Get the fileid from the URL 
  136. // Query the file ID 
  137. $query = sprintf("SELECT * FROM tableName WHERE id = '%s'",mysql_real_escape_string($filename)); 
  138. $sql = mysql_query($query); 
  139. if(mysql_num_rows($sql) > 0){ 
  140.     $row = mysql_fetch_array($sql); 
  141.     // Set some headers 
  142.     header("Pragma: public"); 
  143.     header("Expires: 0"); 
  144.     header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
  145.     header("Content-Type: application/force-download"); 
  146.     header("Content-Type: application/octet-stream"); 
  147.     header("Content-Type: application/download"); 
  148.     header("Content-Disposition: attachment; filename=".basename($row['FileName']).";"); 
  149.     header("Content-Transfer-Encoding: binary"); 
  150.     header("Content-Length: ".filesize($row['FileName'])); 
  151.  
  152.     @readfile($row['FileName']); 
  153.     exit(0); 
  154. }else{ 
  155.     header("Location: /"); 
  156.     exit; 
  157. }
  158. 六、通过Email显示用户的Gravatar头像
  159.  
  160.  $gravatar_link = 'http://www.gravatar.com/avatar/' . md5($comment_author_email) . '?s=32';
  161.   echo '<img src="' . $gravatar_link . '" />';
  162. 七、通过cURL获取RSS订阅数
  163.  
  164. $ch = curl_init();
  165. curl_setopt($ch,CURLOPT_URL,'https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=7qkrmib4r9rscbplq5qgadiiq4');
  166. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  167. curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
  168. $content = curl_exec($ch);
  169. $subscribers = get_match('/circulation="(.*)"/isU',$content);
  170. curl_close($ch);
  171. 八、时间差异计算函数
  172.  
  173. function ago($time)
  174. {
  175.    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
  176.    $lengths = array("60","60","24","7","4.35","12","10");
  177.  
  178.    $now = time();
  179.  
  180.        $difference     = $now - $time;
  181.        $tense         = "ago";
  182.  
  183.    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
  184.        $difference /= $lengths[$j];
  185.    }
  186.  
  187.    $difference = round($difference);
  188.  
  189.    if($difference != 1) {
  190.        $periods[$j].= "s";
  191.    }
  192.  
  193.    return "$difference $periods[$j] 'ago' ";
  194. }
  195. 九、裁剪图片
  196.  
  197. $filename= "test.jpg";
  198. list($w, $h, $type, $attr) = getimagesize($filename);
  199. $src_im = imagecreatefromjpeg($filename);
  200.  
  201. $src_x = '0';   // begin x
  202. $src_y = '0';   // begin y
  203. $src_w = '100'; // width
  204. $src_h = '100'; // height
  205. $dst_x = '0';   // destination x
  206. $dst_y = '0';   // destination y
  207.  
  208. $dst_im = imagecreatetruecolor($src_w, $src_h);
  209. $white = imagecolorallocate($dst_im, 255, 255, 255);
  210. imagefill($dst_im, 0, 0, $white);
  211.  
  212. imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
  213.  
  214. header("Content-type: image/png");
  215. imagepng($dst_im);
  216. imagedestroy($dst_im);
  217. 十、检查网站是否宕机
  218.  
  219. function Visit($url){
  220.        $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init();
  221.        curl_setopt ($ch, CURLOPT_URL,$url );
  222.        curl_setopt($ch, CURLOPT_USERAGENT, $agent);
  223.        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  224.        curl_setopt ($ch,CURLOPT_VERBOSE,false);
  225.        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  226.        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
  227.        curl_setopt($ch,CURLOPT_SSLVERSION,3);
  228.        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
  229.        $page=curl_exec($ch);
  230.        //echo curl_error($ch);
  231.        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  232.        curl_close($ch);
  233.        if($httpcode>=200 && $httpcode<300) return true;
  234.        else return false;
  235. }
  236. if (Visit("http://www.google.com"))
  237.        echo "Website OK"."n";
  238. else
  239.        echo "Website DOWN";