10个典型实用的PHP代码片段

开发 后端
本文将介绍10个经常会用到的PHP代码片段,包括黑名单过滤、随机颜色生成器、从网上下载文件、Alexa/Google Page Rank、强制下载文件、用Email显示用户的Gravator头像、用cURL获取RSS订阅数、截取图片、检查网站是否宕机。

本文将介绍10个经常会用到的PHP代码片段,包括黑名单过滤、随机颜色生成器、从网上下载文件、Alexa/Google Page Rank、强制下载文件、用Email显示用户的Gravator头像、用cURL获取RSS订阅数、截取图片、检查网站是否宕机。

[[151048]]

一、黑名单过滤

 

  1. function is_spam($text$file$split = ':'$regex = false){ 
  2.     $handle = fopen($file'rb'); 
  3.     $contents = fread($handlefilesize($file)); 
  4.     fclose($handle); 
  5.     $lines = explode("n"$contents); 
  6. $arr = array(); 
  7. foreach($lines as $line){ 
  8. list($word$count) = explode($split$line); 
  9. if($regex
  10. $arr[$word] = $count
  11. else 
  12. $arr[preg_quote($word)] = $count
  13. preg_match_all("~".implode('|'array_keys($arr))."~"$text$matches); 
  14. $temp = array(); 
  15. foreach($matches[0] as $match){ 
  16. if(!in_array($match$temp)){ 
  17. $temp[$match] = $temp[$match] + 1; 
  18. if($temp[$match] >= $arr[$word]) 
  19. return true; 
  20. return false; 
  21.  
  22. $file = 'spam.txt'
  23. $str = 'This string has cat, dog word'
  24. if(is_spam($str$file)) 
  25. echo 'this is spam'
  26. else 
  27. echo 'this is not spam'
  28.  
  29. ab:3 
  30. dog:3 
  31. cat:2 
  32. monkey:2 

二、随机颜色生成器

  1. function randomColor() { 
  2.     $str = '#'
  3.     for($i = 0 ; $i < 6 ; $i++) { 
  4.         $randNum = rand(0 , 15); 
  5.         switch ($randNum) { 
  6.             case 10: $randNum = 'A'break
  7.             case 11: $randNum = 'B'break
  8.             case 12: $randNum = 'C'break
  9.             case 13: $randNum = 'D'break
  10.             case 14: $randNum = 'E'break
  11.             case 15: $randNum = 'F'break
  12.         } 
  13.         $str .= $randNum
  14.     } 
  15.     return $str
  16. $color = randomColor(); 

三、从网上下载文件

 

  1. set_time_limit(0); 
  2. // Supports all file types 
  3. // URL Here: 
  4. $url = 'http://somsite.com/some_video.flv'
  5. $pi = pathinfo($url); 
  6. $ext = $pi['extension']; 
  7. $name = $pi['filename']; 
  8.  
  9. // create a new cURL resource 
  10. $ch = curl_init(); 
  11.  
  12. // set URL and other appropriate options 
  13. curl_setopt($ch, CURLOPT_URL, $url); 
  14. curl_setopt($ch, CURLOPT_HEADER, false); 
  15. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
  16. curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
  17. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
  18. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
  19.  
  20. // grab URL and pass it to the browser 
  21. $opt = curl_exec($ch); 
  22.  
  23. // close cURL resource, and free up system resources 
  24. curl_close($ch); 
  25.  
  26. $saveFile = $name.'.'.$ext
  27. if(preg_match("/[^0-9a-z._-]/i"$saveFile)) 
  28. $saveFile = md5(microtime(true)).'.'.$ext
  29.  
  30. $handle = fopen($saveFile'wb'); 
  31. fwrite($handle$opt); 
  32. fclose($handle); 

四、Alexa/Google Page Rank

  1. function page_rank($page$type = 'alexa'){ 
  2. switch($type){ 
  3. case 'alexa'
  4. $url = 'http://alexa.com/siteinfo/'
  5. $handle = fopen($url.$page'r'); 
  6. break
  7. case 'google'
  8. $url = 'http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:'
  9. $handle = fopen($url.'http://'.$page'r'); 
  10. break
  11. $content = stream_get_contents($handle); 
  12. fclose($handle); 
  13. $content = preg_replace("~(n|t|ss+)~",''$content); 
  14. switch($type){ 
  15. case 'alexa'
  16. if(preg_match('~<div class="data (down|up)"><img.+?>(.+?) </div>~im',$content,$matches)){ 
  17. return $matches[2]; 
  18. }else
  19. return FALSE; 
  20. break
  21. case 'google'
  22. $rank = explode(':',$content); 
  23. if($rank[2] != ''
  24. return $rank[2]; 
  25. else 
  26. return FALSE; 
  27. break
  28. default
  29. return FALSE; 
  30. break
  31. // Alexa Page Rank: 
  32. echo 'Alexa Rank: '.page_rank('techug.com'); 
  33. echo ' '
  34. // Google Page Rank 
  35. echo 'Google Rank: '.page_rank('techug.com''google'); 

五、强制下载文件

 

  1. $filename = $_GET['file']; //Get the fileid from the URL 
  2. // Query the file ID 
  3. $query = sprintf("SELECT * FROM tableName WHERE id = '%s'",mysql_real_escape_string($filename)); 
  4. $sql = mysql_query($query); 
  5. if(mysql_num_rows($sql) > 0){ 
  6. $row = mysql_fetch_array($sql); 
  7. // Set some headers 
  8. header("Pragma: public"); 
  9. header("Expires: 0"); 
  10. header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
  11. header("Content-Type: application/force-download"); 
  12. header("Content-Type: application/octet-stream"); 
  13. header("Content-Type: application/download"); 
  14. header("Content-Disposition: attachment; filename=".basename($row['FileName']).";"); 
  15. header("Content-Transfer-Encoding: binary"); 
  16. header("Content-Length: ".filesize($row['FileName'])); 
  17.  
  18. @readfile($row['FileName']); 
  19. exit(0); 
  20. }else
  21. header("Location: /"); 
  22. exit

六、用Email显示用户的Gravator头像

  1. $gravatar_link = 'http://www.gravatar.com/avatar/' . md5($comment_author_email) . '?s=32'
  2. echo '<img src="' . $gravatar_link . '" />'

七、用cURL获取RSS订阅数

  1. $ch = curl_init(); 
  2. curl_setopt($ch,CURLOPT_URL,'https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=7qkrmib4r9rscbplq5qgadiiq4'); 
  3. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
  4. curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2); 
  5. $content = curl_exec($ch); 
  6. $subscribers = get_match('/circulation="(.*)"/isU',$content); 
  7. curl_close($ch);  

八、时间差异计算

 

  1. function ago($time) 
  2.    $periods = array("second""minute""hour""day""week""month""year""decade"); 
  3. $lengths = array("60","60","24","7","4.35","12","10"); 
  4.  
  5. $now = time(); 
  6.  
  7. $difference = $now - $time; 
  8. $tense = "ago"
  9.  
  10. for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 
  11. $difference /= $lengths[$j]; 
  12.  
  13. $difference = round($difference); 
  14.  
  15. if($difference != 1) { 
  16. $periods[$j].= "s"
  17.  
  18. return "$difference $periods[$j] 'ago' "

九、截取图片

 

  1. $filename"test.jpg"
  2. list($w$h$type$attr) = getimagesize($filename); 
  3. $src_im = imagecreatefromjpeg($filename); 
  4.  
  5. $src_x = '0'// begin x 
  6. $src_y = '0'// begin y 
  7. $src_w = '100'// width 
  8. $src_h = '100'// height 
  9. $dst_x = '0'// destination x 
  10. $dst_y = '0'// destination y 
  11.  
  12. $dst_im = imagecreatetruecolor($src_w$src_h); 
  13. $white = imagecolorallocate($dst_im, 255, 255, 255); 
  14. imagefill($dst_im, 0, 0, $white); 
  15.  
  16. imagecopy($dst_im$src_im$dst_x$dst_y$src_x$src_y$src_w$src_h); 
  17.  
  18. header("Content-type: image/png"); 
  19. imagepng($dst_im); 
  20. imagedestroy($dst_im); 

十、检查网站是否宕机

 

  1. function Visit($url){ 
  2.        $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init(); 
  3. curl_setopt ($ch, CURLOPT_URL,$url ); 
  4. curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
  5. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
  6. curl_setopt ($ch,CURLOPT_VERBOSE,false); 
  7. curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
  8. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE); 
  9. curl_setopt($ch,CURLOPT_SSLVERSION,3); 
  10. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE); 
  11. $page=curl_exec($ch); 
  12. //echo curl_error($ch); 
  13. $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
  14. curl_close($ch); 
  15. if($httpcode>=200 && $httpcode<300) return true; 
  16. else return false; 
  17. if (Visit("http://www.google.com")) 
  18. echo "Website OK"."n"
  19. else 
  20. echo "Website DOWN"
责任编辑:王雪燕 来源: 淡忘~浅思
相关推荐

2011-07-07 10:35:53

htaccess

2011-07-14 10:07:19

PHP

2020-11-16 16:04:42

CSS设计代码

2021-09-17 15:31:47

代码JavaScript数组

2015-11-02 09:25:07

jQuery代码片段

2011-11-23 09:21:43

jQuery

2023-06-16 16:34:25

JavaScripWeb 开发

2024-01-04 16:46:58

JavaScript开发

2023-11-03 16:02:00

JavaScript开发

2024-04-09 00:00:00

Java代码片段

2011-09-06 15:16:42

PHP

2015-10-29 10:30:41

C#程序员实用代码

2015-08-19 09:15:11

C#程序员实用代码

2012-01-17 13:54:02

PHP

2019-10-10 16:49:18

Python镜音双子脚本语言

2022-06-08 08:55:15

JavaScript代码前端

2021-10-31 07:36:17

前端JavaScript编程

2023-10-12 15:02:21

PythonPandas数据分析

2015-08-06 13:12:10

PHP代码样例

2011-08-15 09:47:49

PHP
点赞
收藏

51CTO技术栈公众号