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 相关文章推荐
我的论坛源代码(二)
Oct 09 PHP
php 表单数据的获取代码
Mar 10 PHP
PHP foreach循环使用详解与实例代码
May 08 PHP
成为好程序员必须避免的5个坏习惯
Jul 04 PHP
php对象和数组相互转换的方法
May 12 PHP
php数组随机排序实现方法
Jun 13 PHP
PHP扩展迁移为PHP7扩展兼容性问题记录
Feb 15 PHP
PHP在线调试执行的实现方法(附demo源码)
Apr 28 PHP
php实现常见图片格式的水印和缩略图制作(面向对象)
Jun 15 PHP
php file_get_contents取文件中数组元素的方法
Apr 01 PHP
php使用curl实现简单模拟提交表单功能
May 15 PHP
基于 Swoole 的微信扫码登录功能实现代码
Jan 15 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高手?学会“懒惰”的编程
2006/12/05 PHP
php中常用编辑器推荐
2007/01/02 PHP
php数据库密码的找回的步骤
2011/01/12 PHP
php递归使用示例(php递归函数)
2014/02/14 PHP
php实现Linux服务器木马排查及加固功能
2014/12/29 PHP
php获取当前页面完整URL地址
2015/12/30 PHP
PHP获取数组中单列值的方法
2017/06/10 PHP
PHP实现负载均衡下的session共用功能
2018/04/17 PHP
精解window.setTimeout()&amp;window.setInterval()使用方式与参数传递问题!
2007/11/23 Javascript
jQuery调用RESTful WCF示例代码(GET方法/POST方法)
2014/01/26 Javascript
javascript实现点击按钮弹出一个可关闭层窗口同时网页背景变灰的方法
2015/05/13 Javascript
javascript文本模板用法实例
2015/07/31 Javascript
js脚本分页代码分享(7种样式)
2015/08/19 Javascript
基于jQuery实现在线选座之高铁版
2015/08/24 Javascript
jquery实现简单的表单验证
2015/11/17 Javascript
实例讲解jQuery中对事件的命名空间的运用
2016/05/24 Javascript
jQuery ajax方法传递中文时出现中文乱码的解决方法
2016/07/25 Javascript
jQuery购物网页经典制作案例
2016/08/19 Javascript
利用HBuilder打包前端开发webapp为apk的方法
2017/11/13 Javascript
JavaScript中使用import 和require打包后实现原理分析
2018/03/07 Javascript
vue实现底部菜单功能
2018/07/24 Javascript
解决Echarts 显示隐藏后宽度高度变小的问题
2020/07/19 Javascript
解决element-ui的下拉框有值却无法选中的情况
2020/11/07 Javascript
vue脚手架项目创建步骤详解
2021/03/02 Vue.js
python实现下载指定网址所有图片的方法
2015/08/08 Python
Python切片知识解析
2016/03/06 Python
python笔记:mysql、redis操作方法
2017/06/28 Python
Python如何实现MySQL实例初始化详解
2017/11/06 Python
numpy.ndarray 交换多维数组(矩阵)的行/列方法
2018/08/02 Python
对python for 文件指定行读写操作详解
2018/12/29 Python
Django:使用filter的pk进行多值查询操作
2020/07/15 Python
Linux的主要特性
2014/10/06 面试题
我的祖国演讲稿
2014/05/04 职场文书
创业不要错过,这4种餐饮新模式
2019/07/18 职场文书
postman中form-data、x-www-form-urlencoded、raw、binary的区别介绍
2022/01/18 HTML / CSS
解析探秘fescar分布式事务实现原理
2022/02/28 Java/Android