6个超实用的PHP代码片段


Posted in PHP onAugust 10, 2015

一、黑名单过滤

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

四、强制下载文件

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

五、截取图片

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

以上就是6个超实用的PHP代码样例,希望对大家学习PHP编程有所帮助,果断收藏吧

PHP 相关文章推荐
用Flash图形化数据(二)
Oct 09 PHP
php中ob(Output Buffer 输出缓冲)函数使用方法
Jul 21 PHP
mysql 中InnoDB和MyISAM的区别分析小结
Apr 15 PHP
PHP UTF8中文字符截断函数代码
Sep 11 PHP
浅析php学习的路线图
Jul 10 PHP
php学习笔记之面向对象
Nov 08 PHP
php查询mysql数据库并将结果保存到数组的方法
Mar 18 PHP
php实现用于计算执行时间的类实例
Apr 18 PHP
Yii安装与使用Excel扩展的方法
Jul 13 PHP
PHP中SERIALIZE和JSON的序列化与反序列化操作区别分析
Oct 11 PHP
POST一个JSON格式的数据给Restful服务实例详解
Apr 07 PHP
PHP操作Redis数据库常用方法示例
Aug 25 PHP
解读PHP中的垃圾回收机制
Aug 10 #PHP
php实现多城市切换特效
Aug 09 #PHP
php基于双向循环队列实现历史记录的前进后退等功能
Aug 08 #PHP
PHP实现获取文件后缀名的几种常用方法
Aug 08 #PHP
PHP实现多维数组转字符串和多维数组转一维数组的方法
Aug 08 #PHP
Smarty使用自定义资源的方法
Aug 08 #PHP
SESSION存放在数据库用法实例
Aug 08 #PHP
You might like
Ext.data.PagingMemoryProxy分页一次性读取数据的实现代码
2010/04/07 PHP
php 判断是否是中文/英文/数字示例代码
2013/09/30 PHP
php使用mysqli向数据库添加数据的方法
2015/03/20 PHP
分享3个php获取日历的函数
2015/09/25 PHP
实现局部遮罩与关闭原理及代码
2013/02/04 Javascript
jQuery事件绑定.on()简要概述及应用
2013/02/07 Javascript
js调用css属性写法
2013/09/21 Javascript
html+js实现动态显示本地时间
2013/09/21 Javascript
清除div下面的所有标签的方法
2014/02/17 Javascript
JavaScript字符串对象split方法入门实例(用于把字符串分割成数组)
2014/10/16 Javascript
JavaScript数组随机排列实现随机洗牌功能
2015/03/19 Javascript
Nodejs实现批量下载妹纸图
2015/05/28 NodeJs
jquery实现的3D旋转木马特效代码分享
2015/08/25 Javascript
Bootstrap入门书籍之(三)栅格系统
2016/02/17 Javascript
详解AngularJS控制器的使用
2016/03/09 Javascript
jQuery实现简洁的轮播图效果实例
2016/09/07 Javascript
vue-router3.0版本中 router.push 不能刷新页面的问题
2018/05/10 Javascript
微信小程序全选多选效果实现代码解析
2020/01/21 Javascript
three.js着色器材质的内置变量示例详解
2020/08/16 Javascript
通过滑动翻页效果实现和移动端click事件问题
2021/01/26 Javascript
[58:37]Serenity vs Fnatic 2018国际邀请赛淘汰赛BO1 8.21
2018/08/22 DOTA
将string类型的数据类型转换为spark rdd时报错的解决方法
2019/02/18 Python
详解如何管理多个Python版本和虚拟环境
2019/05/10 Python
numpy:np.newaxis 实现将行向量转换成列向量
2019/11/30 Python
深入了解Python 方法之类方法 &amp; 静态方法
2020/08/17 Python
python 利用toapi库自动生成api
2020/10/19 Python
10个最常见的HTML5面试题 附答案
2016/06/06 HTML / CSS
Moss Bros官网:英国排名第一的西装店
2020/02/26 全球购物
.NET是怎么支持多种语言的
2015/02/24 面试题
临床专业自荐信
2014/06/22 职场文书
2015年大学班长个人工作总结
2015/04/24 职场文书
建党伟业电影观后感
2015/06/01 职场文书
篮球赛新闻稿
2015/07/17 职场文书
医院病假条范文
2015/08/17 职场文书
2015年党风廉政建设个人总结
2015/08/18 职场文书
警用民用对讲机找不同
2022/02/18 无线电