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 相关文章推荐
第十一节 重载 [11]
Oct 09 PHP
PHP 函数语法介绍一
Jun 14 PHP
FirePHP 推荐一款PHP调试工具
Apr 23 PHP
超级实用的7个PHP代码片段分享
Jan 05 PHP
PHP的preg_match匹配字符串长度问题解决方法
May 03 PHP
php中使用session_set_save_handler()函数把session保存到MySQL数据库实例
Nov 06 PHP
PHP图像处理类库MagickWand用法实例分析
May 21 PHP
php实现XML和数组的相互转化功能示例
Feb 08 PHP
PHP判断是否微信访问的方法示例
Mar 27 PHP
TP5.0框架实现无限极回复功能的方法分析
May 04 PHP
Laravel中validation验证 返回中文提示 全局设置的方法
Sep 29 PHP
在 Laravel 中动态隐藏 API 字段的方法
Oct 25 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
Laravel如何友好的修改.env配置文件详解
2017/06/07 PHP
textarea的value是html文件源代码,存成html文件的代码
2007/04/20 Javascript
改版了网上的一个js操作userdata
2007/04/27 Javascript
javascript支持firefox,ie7页面布局拖拽效果代码
2007/12/20 Javascript
jQuery学习笔记(3)--用jquery(插件)实现多选项卡功能
2013/04/08 Javascript
动态加载JS文件的三种方法
2013/11/08 Javascript
JavaScript面向对象之私有静态变量实例分析
2016/01/14 Javascript
Javascript的表单验证-提交表单
2016/03/18 Javascript
Node.js和Express简单入门介绍
2017/03/24 Javascript
微信小程序中使用javascript 回调函数
2017/05/11 Javascript
Webpack打包css后z-index被重新计算的解决方法
2017/06/18 Javascript
axios 处理 302 状态码的解决方法
2018/04/10 Javascript
JS 实现获取验证码 倒计时功能
2018/10/29 Javascript
vue 自定义组件的写法与用法详解
2020/03/04 Javascript
基于JavaScript实现控制下拉列表
2020/05/08 Javascript
[50:29]2014 DOTA2华西杯精英邀请赛 5 24 DK VS iG
2014/05/26 DOTA
[15:39]教你分分钟做大人:龙骑士
2014/10/30 DOTA
python遍历 truple list dictionary的几种方法总结
2016/09/11 Python
python如何为创建大量实例节省内存
2018/03/20 Python
python实现图像拼接功能
2020/03/23 Python
Python打印特殊符号及对应编码解析
2020/05/07 Python
python实现简单文件读写函数
2021/02/25 Python
美国孩之宝玩具官网:Hasbro Pulse
2019/06/24 全球购物
求职信格式范本
2013/11/15 职场文书
服装采购员岗位职责
2014/03/15 职场文书
综治宣传月活动总结
2014/04/28 职场文书
投标单位介绍信
2015/05/05 职场文书
校园歌手大赛主持词
2015/07/03 职场文书
2015年教师节主持词
2015/07/03 职场文书
离职告别感言
2015/08/04 职场文书
2016年校园重阳节广播稿
2015/12/18 职场文书
2016年小学“公民道德宣传日”活动总结
2016/04/01 职场文书
Go timer如何调度
2021/06/09 Golang
MySQL 开窗函数
2022/02/15 MySQL
PyCharm 配置SSH和SFTP连接远程服务器
2022/05/11 Python
Java实现贪吃蛇游戏的示例代码
2022/09/23 Java/Android