PHP开发中常用的十个代码样例


Posted in PHP onFebruary 02, 2016

一、黑名单过滤

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

四、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(‘~<div class="data (down|up)"><img.+?>(.+?) </div>~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‘);

五、强制下载文件

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

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

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

七、用cURL获取RSS订阅数

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

八、时间差异计算

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‘ "; 
}

九、截取图片

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

十、检查网站是否宕机

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

以上内容针对PHP开发中常用的十个代码样例做了总结,希望对大家有所帮助。

PHP 相关文章推荐
smarty实例教程
Nov 19 PHP
php 面向对象的一个例子
Apr 12 PHP
php中++i 与 i++ 的区别
Aug 08 PHP
PHP小技巧之函数重载
Jun 02 PHP
php实现扫描二维码根据浏览器类型访问不同下载地址
Oct 15 PHP
php的dl函数用法实例
Nov 06 PHP
php数组转成json格式的方法
Mar 09 PHP
在Linux系统的服务器上隐藏PHP版本号的方法
Jun 06 PHP
php实现word转html的方法
Jan 22 PHP
thinkPHP简单调用函数与类库的方法
Mar 15 PHP
PHP超级全局变量【$GLOBALS,$_SERVER,$_REQUEST等】用法实例分析
Dec 11 PHP
php实现断点续传大文件示例代码
Jun 19 PHP
必须收藏的php实用代码片段
Feb 02 #PHP
PHP执行linux命令常用函数汇总
Feb 02 #PHP
必须收藏的23个php实用代码片段
Feb 02 #PHP
如何批量清理系统临时文件(语言:C#、 C/C++、 php 、python 、java )
Feb 01 #PHP
PHP自带方法验证邮箱是否存在
Feb 01 #PHP
YII CLinkPager分页类扩展增加显示共多少页
Jan 29 #PHP
实例详解PHP中html word 互转的方法
Jan 28 #PHP
You might like
Zend Framework教程之模型Model用法简单实例
2016/03/04 PHP
浅析PHP中的i++与++i的区别及效率
2016/06/15 PHP
php中preg_replace_callback函数简单用法示例
2016/07/21 PHP
老生常谈文本文件和二进制文件的区别
2017/02/27 PHP
JSChart轻量级图形报表工具(内置函数中文参考)
2010/10/11 Javascript
jquery 面包屑导航 具体实现
2013/06/05 Javascript
jQuery瀑布流插件Wookmark使用实例
2014/04/02 Javascript
js动态添加onclick事件可传参数与不传参数
2014/07/29 Javascript
Javascript中call与apply的学习笔记
2014/09/22 Javascript
JavaScript中Function()函数的使用教程
2015/06/04 Javascript
nodejs创建web服务器之hello world程序
2015/08/20 NodeJs
JavaScript程序设计之JS调试
2015/12/09 Javascript
js密码强度实时检测代码
2016/03/02 Javascript
bootstrap suggest搜索建议插件使用详解
2017/03/25 Javascript
JavaScript30 一个月纯 JS 挑战中文指南(英文全集)
2017/07/23 Javascript
详解bootstrap导航栏.nav与.navbar区别
2017/11/23 Javascript
Node.Js生成比特币地址代码解析
2018/04/21 Javascript
快速解决select2在bootstrap模态框中下拉框隐藏的问题
2018/08/10 Javascript
Vue起步(无cli)的啊教程详解
2019/04/11 Javascript
微信小程序保存图片到相册权限设置
2020/04/09 Javascript
[43:33]EG vs Spirit Supermajor 败者组 BO3 第一场 6.4
2018/06/05 DOTA
Python内置函数bin() oct()等实现进制转换
2012/12/30 Python
使用Node.js和Socket.IO扩展Django的实时处理功能
2015/04/20 Python
python 把数据 json格式输出的实例代码
2016/10/31 Python
对pandas replace函数的使用方法小结
2018/05/18 Python
Pytorch mask-rcnn 实现细节分享
2020/06/24 Python
旧时光糖果:Old Time Candy
2018/02/05 全球购物
《大禹治水》教学反思
2014/04/27 职场文书
2014社区健康教育工作总结
2014/12/16 职场文书
通知书大全
2015/04/27 职场文书
美丽的大脚观后感
2015/06/03 职场文书
法律讲堂观后感
2015/06/11 职场文书
2015小学新教师个人工作总结
2015/10/14 职场文书
2019年朋友圈经典励志语录50条
2019/07/05 职场文书
「月刊Action」2022年5月号封面公开
2022/03/21 日漫
《帝国时代4》赛季预告 新增内容编译器可创造地图
2022/04/03 其他游戏