10个开发中常用的PHP代码样例
一、黑名单过滤
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";
10个开发中常用的PHP代码样例的更多相关文章
- NC65在日常开发中常用的代码写法
标题 NC65开发相关代码 版本 1.0.1 作者 walton 说明 收集NC在日常开发中常用的代码写法,示例展示 1.查询 1.1 通过BaseDAO查询结果集并转换 //通过BaseDAO进行查 ...
- 开发中常用的Hook
开发中常用的Hook 什么是Hook? Hook 是一些可以让你在函数组件里"钩入" React state 及生命周期等特性的函数,用来实现一些 class 组件的特性的. 1 ...
- .net开发中常用的第三方组件
.net开发中常用的第三方组件 2013-05-09 09:33:32| 分类: dotnet |举报 |字号 订阅 下载LOFTER 我的照片书 | RSS.NET.dll RSS. ...
- spring注解开发中常用注解以及简单配置
一.spring注解开发中常用注解以及简单配置 1.为什么要用注解开发:spring的核心是Ioc容器和Aop,对于传统的Ioc编程来说我们需要在spring的配置文件中邪大量的bean来向sprin ...
- Android源码浅析(四)——我在Android开发中常用到的adb命令,Linux命令,源码编译命令
Android源码浅析(四)--我在Android开发中常用到的adb命令,Linux命令,源码编译命令 我自己平时开发的时候积累的一些命令,希望对你有所帮助 adb是什么?: adb的全称为Andr ...
- 2019-2-20C#开发中常用加密解密方法解析
C#开发中常用加密解密方法解析 一.MD5加密算法 我想这是大家都常听过的算法,可能也用的比较多.那么什么是MD5算法呢?MD5全称是 message-digest algorithm 5[|ˈmes ...
- 开发中常用的es6知识
结合实际开发,开发中常用的es6的知识: 1.新增let和const命令: ES6 新增了let命令,用来声明变量.它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效: cons ...
- iOS开发中常用的数学函数
iOS开发中常用的数学函数 /*---- 常用数学公式 ----*/ //指数运算 3^2 3^3 NSLog(,)); //result 9 NSLog(,)); //result 27 //开平方 ...
- 开发中常用Fel的写法
直接看代码吧: package javademo; import java.util.HashMap;import java.util.Map; import com.greenpineyu.fel. ...
随机推荐
- 一处疑难杂症的术后总结:WebView和JavaScript之间的交互
近期在公司里參与了M3项目的开发,这个项目是使用HTML5开发的前端页面,在开发完成后,把项目地址写入Android.iOS的壳源代码里面,这样当应用被打开时候自己主动加载项目首页的URL.这样的做法 ...
- [svc]caffe安装笔记
以前是word排版,加上没有些技术博客经验,相当的糟心. 现在想改,发现博文太多,找不到对应在那一页了,所以老的博文留着吧. caffe,这是是数据组需要做一些大数据模型的训练(深度学习), 要求 服 ...
- [na]802.1x协议无线认证协议&dot1x有线认证实验
以前搞无线时候,会涉及到无线client接入方式的认证协议. 认证方式+加密方式+有线的dot1x. 注:以前都是doc粘贴到博客的,加上没写博客的习惯,因此会比较乱. EAP(扩展认证协议)是什么? ...
- nc 传输文件
在接收服务器上执行:(123.57.36.227) [root@ ~]# cat /tmp/user.txt hello world [root@ ~]# nc -v -l -p >/tmp/u ...
- Linux,Windows中的相对路径、绝对路径
1.Windows绝对路径:以盘符开始 如C:/a.txt相对路径:. 指的是当前目录.. 指的是挡圈目录的上一级目录./test表示当前目录下的test文件夹/test表示当前盘符下的test文件夹 ...
- 20个可能你不知道Linux网路工具
如果要在你的系统上监控网络,那么使用命令行工具是非常实用的,并且对于 Linux 用户来说,有着许许多多现成的工具可以使用,如: nethogs, ntopng, nload, iftop, iptr ...
- 关于 \t 水平制表符 Horizontal Tab (TAB)
今天在学learn python the hard way ex26修改的时候,有一个关于\t的问题,下面分别为代码以及输出结果: 1 poem = """ 2 \tTh ...
- dubbo注册zookeeper保错原因
我的zookeeper是安装在本地,用的默认端口2181,版本3.4.10.dubbo版本2.5.8.dubbo-demo-provider.xml配置文件修改为:<dubbo:registry ...
- Python的sys.argv使用说明 通过终端写入环境变量
刚开始使用这个参数的时候,很不明白其含义.网上搜索很多都是贴的官网上面的一则实例,说看懂,就明白.可是,我看不懂.现在在回头看这个参数使用,并不是很麻烦. 举几个小例子就明白了. 创建一个脚本,内容如 ...
- Windows下 Pycharm连接Github 教程
Pycharm连接Github 绑定账号 1.File->Settings->Version Control->Github Settings.png 会出现github,然后在旁边 ...