10个有用的php代码实例_php按需求改代码的例子_wming3的博客-程序员秘密

技术标签: 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显示用户的Gravatar头像

 $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";
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010187139/article/details/42176455

智能推荐

目标跟踪算法——KCF入门详解_kcf算法_小小菜鸟一只的博客-程序员秘密

一直以来没有很想写这个,以为这个东西比较简单,还算是比较容易理解的一个算法,但是在知乎上回答过一个问题之后就有朋友私信我一些关于细节的东西,我一直以为关于细节的东西大家可以自己去理解,大家都是想快速了解这个,那我就厚脸皮了在这写一下自己的见解了,如果有写的不详细或者大家想了解的东西没写到的都可以留言,我给补充上去。———————————————————————————————————————————

深度学习在OCR中的应用论文及代码集锦 (1)_frank_hetest的博客-程序员秘密

[1] PixelLink: Detecting SceneText via Instance SegmentationDan Deng et al.AAAI 2018...

(转)大神学长给我们的书目,好多好残暴(结尾附上pdf地址)_deadxing的博客-程序员秘密

推荐书目:基础类:《PHP基础教程》 - PHP大神推荐,PHP入门经典。《PHP与MySQL权威指南》 - 主要推荐其中的MYSQL部分,如果对数据库不熟悉,可能会影响到后面SQL注入的学习。《Javascript权威指南》 - XSS的基础,如果JS不熟练的话,可能XSS攻击也不会很熟练。学习JS有助于后续的XSS攻击的学习。《Python基础教程》 - 写脚本必备的编

千万不要一辈子靠技术生存_码农突围的博客-程序员秘密

点击上方“码农突围”,马上关注,真爱,请"星标"来源:apkbus.com/blog-822717-80431.html一、前言二、技术最强不等于一定会受到他人的尊重三、...

一种简便实用的自定义LOG实现(iOS)_Ethan. L的博客-程序员秘密

系统自带的NSLog功能相对单一。在调试过程中,为了使NSLog功能更强大,有两种方法实现:1. 引入DDLog第三方框架,这个框架非常强大,可以生成日志。2.使用轻量级的自动以LOG,方法如下:#define NEED_DEBUG#ifdef NEED_DEBUG#define NSLog(format, ...) \    do { \        N

菜鸟教程html5常用标签,HTML5 Canvas | w3cschool菜鸟教程_weixin_39549899的博客-程序员秘密

HTML5 Canvas 标签定义图形,比如图表和其他图像,您必须使用脚本来绘制图形。。在画布上(Canvas)画一个红色矩形,梯度矩形,彩色矩形,和一些彩色的文字。你的浏览器不支持 HTML5 的 元素.什么是 Canvas?HTML5 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成. 标签只是图形容器,您必须使用脚本来绘制图形。你可以通过多种方法使用Canva绘制路径,盒...

随便推点

VC工程改名的方法_vc工程中source文件怎么改名_irr80的博客-程序员秘密

额,今天早上比较无聊,于是准备倒腾一个MFC的小程序,又懒得重新设计窗口啊·通信模型啊什么的,于是就想找办法把以前弄过的一个作为模板,改个名字就OK。嘿嘿,方法似乎试过之后,还是蛮简单的,只要用写字本打开dsw、dsp以及rc文件,把里面的原来的那个工程名,替换为现在想改

Java从键盘获取输入(不知道输入个数)——java中Scanner的hasNext()死循环_陌上花开可缓缓归矣___的博客-程序员秘密

问题最近在使用Scanner类中的hasNest()方法进行键盘输入时,发现while循环老是停在那儿,等待输入,而不执行后面的语句。比如这样一段代码:import java.util.ArrayList;import java.util.Scanner;public class blogTest { public static void main(String[] ar...

php eureka客户端,Spring Cloud Eureka 注册与发现操作步骤详解_何之源的博客-程序员秘密

在搭建Spring Cloud Eureka环境前先要了解整个架构的组成,常用的基础模式如下图:服务提供者:将springboot服务编写好以后,通过配置注册中心地址方式注册,提供给消费者使用。注册中心:服务的中间桥梁,服务提供者将服务注册。服务消费者可以通过注册信息调用需要使用的服务。服务消费者:通过规定的调用方式,读取注册中心的注册信息,调用相应的服务。根据后续的服务复杂度进化以后,可以看到服...

英文标点符号翻译大全_weixin_30872499的博客-程序员秘密

英文标点符号翻译大全 +  plus 加号;正号 -  minus 减号;负号 ± plus or minus 正负号 × is multiplied by 乘号 ÷ is divided by 除号 = is equal to 等于号 ≠ is not equal to 不等于号 ≡ is equivalent to 全等于号 ≌ is equal to or approximately equ...

opencv-python根据阈值进行二值化_三个臭皮姜的博客-程序员秘密

继上一篇文章Opencv+python打开摄像头拖动滑动条取颜色阈值得到阈值之后,我们需要对图片进行二值化,怕自己忘了不好找,特此记录一下。#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2021/5/24 19:38# @Author : 若谷# @File : 根据选出的阈值二值化.py# @Software: PyCharmimport cv2import numpy as npframe = cv2.imread('./

【多重背包】51nod 1086 背包问题 V2_笑对这个世界的志贵的博客-程序员秘密

Problem Description 有N种物品,每种物品的数量为C1,C2……Cn。从中任选若干件放在容量为W的背包里,每种物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。Input 第1行,2个整数,N和W中间用空格隔开。N为物品的种类,W为背包的容量。(1 <= N <= 100,1 <= W <= 500

推荐文章

热门文章

相关标签