副标题[/!--empirenews.page--]
本文将介绍10个经常会用到的PHP代码片段,包括黑名单过滤、随机颜色生成器、从网上下载文件、Alexa/Google Page Rank、强制下载文件、用Email显示用户的Gravator头像、用cURL获取RSS订阅数、截取图片、检查网站是否宕机。
一、黑名单过滤
- 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
二、随机颜色生成器
- 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();
三、从网上下载文件
- 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);
(编辑:广州站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|