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 相关文章推荐
php导入导出excel实例
Oct 25 PHP
ThinkPHP的模版中调用session数据的方法
Jul 01 PHP
php实现httpRequest的方法
Mar 13 PHP
怎样搭建PHP开发环境
Jul 28 PHP
php while循环控制的简单实例
May 30 PHP
PHP空值检测函数与方法汇总
Nov 19 PHP
PHP面向对象之里氏替换原则简单示例
Apr 08 PHP
ThinkPHP3.2框架自定义配置和加载用法示例
Jun 14 PHP
PHP常量define和const的区别详解
May 18 PHP
Laravel重定向,a链接跳转,控制器跳转示例
Oct 22 PHP
Laravel5.1 框架路由基础详解
Jan 04 PHP
php操作redis数据库常见方法实例总结
Feb 20 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引用计数器进行垃圾收集机制介绍
2012/09/19 PHP
基于Linux调试工具strace与gdb的常用命令总结
2013/06/03 PHP
thinkphp验证码的实现(form、ajax实现验证)
2016/07/28 PHP
php 变量引用与变量销毁机制详细介绍
2016/12/05 PHP
Laravel学习笔记之Artisan命令生成自定义模板的方法
2018/11/22 PHP
js创建元素(节点)示例
2014/01/02 Javascript
jQuery实现简单网页遮罩层/弹出层效果兼容IE6、IE7
2014/06/16 Javascript
js在IE与firefox的差异集锦
2014/11/11 Javascript
vue实现可增删查改的成绩单
2016/10/27 Javascript
NodeJS配置HTTPS服务实例分享
2017/02/19 NodeJs
angular6 填坑之sdk的方法
2018/12/27 Javascript
浅谈JavaScript中你可能不知道URL构造函数的属性
2020/07/13 Javascript
Vue切换组件实现返回后不重置数据,保留历史设置操作
2020/07/21 Javascript
node.js文件的复制、创建文件夹等相关操作
2021/02/05 Javascript
[00:47]DOTA2荣耀之路6:玩不了啦!
2018/05/30 DOTA
[41:08]TNC vs VG 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
Python多线程编程(三):threading.Thread类的重要函数和方法
2015/04/05 Python
利用Python中SocketServer 实现客户端与服务器间非阻塞通信
2016/12/15 Python
Python调用ctypes使用C函数printf的方法
2017/08/23 Python
python生成每日报表数据(Excel)并邮件发送的实例
2019/02/03 Python
python3读取图片并灰度化图片的四种方法(OpenCV、PIL.Image、TensorFlow方法)总结
2019/07/04 Python
Pycharm+django2.2+python3.6+MySQL实现简单的考试报名系统
2019/09/05 Python
python实现超市管理系统(后台管理)
2019/10/25 Python
Pytorch 之修改Tensor部分值方式
2019/12/27 Python
新手学python应该下哪个版本
2020/06/11 Python
凯蒂·佩里个人女鞋品牌:Katy Perry Collections
2019/04/04 全球购物
GWT (Google Web Toolkit)有哪些主要的原件组成?
2015/06/08 面试题
本科生学习总结的自我评价
2013/10/02 职场文书
教师年终个人自我评价
2013/10/04 职场文书
cf收人广告词大全
2014/03/14 职场文书
房产转让协议书(2014版)
2014/09/30 职场文书
小学见习报告
2014/10/31 职场文书
2015年物业管理员工工作总结
2015/10/15 职场文书
2016年第32个教师节红领巾广播稿
2015/12/18 职场文书
七年级作文之《我和我的祖国》观后感作文
2019/10/18 职场文书
mapstruct的用法之qualifiedByName示例详解
2022/04/06 Java/Android