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 相关文章推荐
给初学者的30条PHP最佳实践(荒野无灯)
Aug 02 PHP
PHP PDOStatement:bindParam插入数据错误问题分析
Nov 13 PHP
php出现web系统多域名登录失败的解决方法
Sep 30 PHP
php的闭包(Closure)匿名函数详解
Feb 22 PHP
深入探究PHP的多进程编程方法
Aug 18 PHP
php根据用户语言跳转相应网页
Nov 04 PHP
在WordPress中获取数据库字段内容和添加主题设置菜单
Jan 11 PHP
Symfony2实现在controller中获取url的方法
Mar 18 PHP
使用composer 安装 laravel框架的方法图文详解
Aug 02 PHP
php获取微信openid方法总结
Oct 10 PHP
php经典趣味算法实例代码
Jan 21 PHP
thinkphp5 redis缓存新增方法实例讲解
Mar 24 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
php实现的太平洋时间和北京时间互转的自定义函数分享
2014/08/19 PHP
php抓取网站图片并保存的实现方法
2015/10/29 PHP
JQuery 获得绝对,相对位置的坐标方法
2010/02/09 Javascript
js判断undefined类型,undefined,null, 的区别详细解析
2013/12/16 Javascript
javascript中var的重要性分析
2015/02/11 Javascript
JS生成某个范围的随机数【四种情况详解】
2016/04/20 Javascript
javascript实现抽奖程序的简单实例
2016/06/07 Javascript
JS获取IE版本号与HTML设置IE文档模式的方法
2016/10/09 Javascript
JS实现汉字与Unicode码相互转换的方法详解
2017/04/28 Javascript
Vue2单一事件管理组件通信
2017/05/09 Javascript
vue父子组件的嵌套的示例代码
2017/09/08 Javascript
React中的refs的使用教程
2018/02/13 Javascript
解决vue中使用Axios调用接口时出现的ie数据处理问题
2018/08/13 Javascript
详解JavaScript中操作符和表达式
2018/09/12 Javascript
对angularJs中自定义指令replace的属性详解
2018/10/09 Javascript
微信小程序实现锚点功能
2019/11/20 Javascript
JS基础之逻辑结构与循环操作示例
2020/01/19 Javascript
详细解析Python中__init__()方法的高级应用
2015/05/11 Python
python 实现分页显示从es中获取的数据方法
2018/12/26 Python
python实现Excel文件转换为TXT文件
2019/04/28 Python
python如何实现视频转代码视频
2019/06/17 Python
python opencv将图片转为灰度图的方法示例
2019/07/31 Python
tensorflow ckpt模型和pb模型获取节点名称,及ckpt转pb模型实例
2020/01/21 Python
Python转换itertools.chain对象为数组的方法
2020/02/07 Python
Python Dataframe常见索引方式详解
2020/05/27 Python
python 下载文件的几种方法汇总
2021/01/06 Python
HTML5几个设计和修改的页面范例分享
2015/09/29 HTML / CSS
远程Wi-Fi宠物监控相机:Petcube
2017/04/26 全球购物
澳大利亚游乐场设备品牌:Lifespan Kids
2019/05/24 全球购物
LUISAVIAROMA德国官网:时尚奢侈品牌购物网站
2020/11/12 全球购物
大学自荐信
2013/12/12 职场文书
小学德育工作经验交流材料
2014/05/22 职场文书
行政工作试用期自我评价
2014/09/14 职场文书
个人查摆剖析材料
2014/10/04 职场文书
解决numpy和torch数据类型转化的问题
2021/05/23 Python
Windows Server 修改远程桌面端口的实现
2022/06/25 Servers