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 相关文章推荐
PHP默认安装产生系统漏洞
Oct 09 PHP
PHP 和 MySQL 开发的 8 个技巧
Oct 09 PHP
php Static关键字实用方法
Jun 04 PHP
比较全面的PHP数组的使用方法小结
Sep 23 PHP
CentOS 6.2使用yum安装LAMP以及phpMyadmin详解
Jun 17 PHP
php生成过去100年下拉列表的方法
Jul 20 PHP
php版阿里大于(阿里大鱼)短信发送实例详解
Nov 30 PHP
PHP 根据key 给二维数组分组
Dec 09 PHP
PHP实现的下载远程文件类定义与用法示例
Jul 05 PHP
Yii2第三方类库插件Imagine的安装和使用
Jul 06 PHP
PHP 二维array转换json的实例讲解
Aug 21 PHP
Yii框架操作cookie与session的方法实例详解
Sep 04 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
PHP中文处理 中文字符串截取(mb_substr)和获取中文字符串字数
2011/11/10 PHP
PHP与Java进行通信的实现方法
2013/10/21 PHP
php防止伪造数据从地址栏URL提交的方法
2014/08/24 PHP
thinkPHP商城公告功能开发问题分析
2016/12/01 PHP
jQuery源码分析-04 选择器-Sizzle-工作原理分析
2011/11/14 Javascript
qTip2 精致的基于jQuery提示信息插件
2012/02/17 Javascript
当json键为数字时的取值方法解析
2013/11/15 Javascript
javascript使用正则表达式检测IP地址
2014/12/03 Javascript
原生javascript实现简单的datagrid数据表格
2015/01/02 Javascript
js检测用户输入密码强度
2015/10/22 Javascript
jQuery实现单击按钮遮罩弹出对话框效果(1)
2017/02/20 Javascript
Angular 4依赖注入学习教程之组件服务注入(二)
2017/06/04 Javascript
基于原生js运动方式关键点的总结(推荐)
2017/10/01 Javascript
Vue中props的使用详解
2018/06/15 Javascript
vue路由中前进后退的一些事儿
2019/05/18 Javascript
layer父页获取弹出层输入框里面的值方法
2019/09/02 Javascript
jQuery实现小火箭返回顶部特效
2020/02/03 jQuery
JS 逻辑判断不要只知道用 if-else 和 switch条件判断(小技巧)
2020/05/27 Javascript
vue 在methods中调用mounted的实现操作
2020/08/07 Javascript
[04:48]DOTA2亚洲邀请赛林书豪为VGJ加油
2017/04/01 DOTA
Python实现的文本简单可逆加密算法示例
2017/05/18 Python
Django如何将URL映射到视图
2019/07/29 Python
Python GUI编程学习笔记之tkinter控件的介绍及基本使用方法详解
2020/03/30 Python
Python configparser模块操作代码实例
2020/06/08 Python
Numpy(Pandas)删除全为零的列的方法
2020/09/11 Python
jupyter notebook 写代码自动补全的实现
2020/11/02 Python
python开发一个解析protobuf文件的简单编译器
2020/11/17 Python
CSS3 实用技巧:实现黑白图像效果示例代码
2013/07/11 HTML / CSS
澳大利亚小众服装品牌:Maurie & Eve
2018/03/27 全球购物
Under Armour安德玛意大利官网:美国高端运动科技品牌
2020/01/16 全球购物
2014年单位植树节活动方案
2014/03/23 职场文书
年终奖发放方案
2014/06/02 职场文书
公司租房协议书范本
2014/10/08 职场文书
2014年党总支工作总结
2014/12/18 职场文书
先进班组材料范文
2014/12/25 职场文书
Java 多线程并发FutureTask
2022/06/28 Java/Android