以前的php代码段

很久以前没随着硬盘被销毁的php代码段

验证码
<?php   
/**
 * 简单的图像类库,本类中所有相对路径均基于网站根目录,如需修改,则修改常量__WEBROOT__即可
 * 功能:指定文字内容创建图片(不支持中文)、创建验证码图片、创建缩略图、其他功能待续
 * 方法:
 *      Style(array $Options) 设置图片样式,每次设定前将重置为默认样式
 *      Create_Img_Png() 创建PNG图像,相关属性由Style指定
 *      Create_Img_Jpeg() 创建JPEG图像,相关属性由Style指定
 *      Create_Verify() 创建验证码图像,相关属性由Style指定
 *      Get_Verify() 获得创建的验证码值,MD5加密
 *      Load_Img(string $FilePath) 加载图像,创建图像源,供其他方法调用源,FilePath为图像相对路径
 *      Create_Thumb(string $FileName,string $FilePath) 创建由Load_Img()加载的图像的缩略图,FileName为保存后的图像前缀,FilePath为保存图像的相对路径,不包含文件名(例:/Uploads/images/Thumb/)
 */

if(!defined("__WEBROOT__")) define("__WEBROOT__",$_SERVER['DOCUMENT_ROOT']);

class Img {
    protected $_Img="D:/phpStudy2016/WWW/lisence/source/3.png"; //图片源
    protected $_FileImg; //加载的图片源
    protected $_FileInfo; //加载的图片的信息数组
    protected $_PicInfo; //加载的图片的宽高等信息数组
    protected $_Rand = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ1234567890'; //随机因子
    protected $_Code = ''; //验证码
    public $Width = 300;//图片默认宽
    public $Height = 80; //图片默认高
    public $BackgroundColor = "000000";
    public $Font = "/phps/Public/Font/ARIALNB.TTF"; //默认字体
    public $FontSize = 16; //默认字体字号
    public $FontColor = "ffffff"; //默认字体颜色
    public $Content = "Test Word";
    public $Align = "left";
    public $Codes = 4; //验证码个数
    public $Line = 6; //干扰线条的个数W
    public $LoadErr = ''; //错误信息

    //public function __construct(){}

    /** 设置图片属性
     * @param array $Options 属性数组
     * @return $this 返回对象
     */
    public function Style($Options){
        $this -> _Re_Set();
        foreach($Options as $K=>$V){
            if(in_array($K,array('Width','Height','BackgroundColor','Font','FontSize','FontColor','Content','Align','Codes','Line','Snow'))){
                if($K == "BackgroundColor" || $K == "FontColor"){
                    if(preg_match("#([a-zA-Z0-9]{6})#",$V)) $this -> $K = $V;
                }else{
                    $this -> $K = $V;
                }
            }
        }
        return $this;
    }

    /**
     * 重置属性,不提供外部访问
     */
    protected function _Re_Set(){
        $this -> Width = 100;
        $this -> Height = 30;
        $this -> BackgroundColor = "000000";
        $this -> Font = "/phps/Public/Font/ARIALNB.TTF";
        $this -> FontSize = 16;
        $this -> FontColor = "ffffff";
        $this -> Align = "left";
        $this -> Codes =4;
        $this -> Line = 6;
    }

    /**
     * 创建图像源、添加背景、创建图像
     * @param bool $BGC 指定是否创建背景色及矩形块
     */
    protected function _Create_Img_GB($BGC = True){
        $this -> _Img = imagecreatetruecolor($this -> Width,$this -> Height); //创建背景源
        if($BGC){
            preg_match("#([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})#",$this -> BackgroundColor,$ColorArr); //将颜色值分隔成三组16位进制数
            $Color = imagecolorallocate($this -> _Img,hexdec($ColorArr[1]),hexdec($ColorArr[2]),hexdec($ColorArr[3])); //给Img图像源添加背景色
            imagefilledrectangle($this -> _Img,0,$this -> Height,$this -> Width,0,$Color); //创建图像
        }
    }

    /**
     * 创建随机验证码
     */
    protected function _Create_Code(){
        $Len = strlen($this -> _Rand) - 1;
        for($i = 0;$i < $this -> Codes;$i++){
            $this -> _Code .= $this -> _Rand[mt_rand(0,$Len)];
        }
    }

    /**
     * 向图像中写入字符串,暂不支持中文
     */
    protected function _Write_Text(){
        $FontWidth = imagefontwidth($this -> FontSize); //获取字号的一个字符的宽度
        preg_match_all('/(.)/us', $this -> Content, $TextArr); //将内容分隔成数组一遍统计个数
        $FontHeight = imagefontheight($this -> FontSize); //获取字号的高度
        $X = ceil(($this -> Width - ($FontWidth * count($TextArr[0]))) / 2); //设置X轴距左边距的距离
        $Y = ceil(($this -> Height + $FontHeight) / 2); //设置Y轴距上边距的距离
        preg_match("#([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})#",$this -> FontColor,$ColorArr);
        $Color = imagecolorallocate($this -> _Img,hexdec($ColorArr[1]),hexdec($ColorArr[2]),hexdec($ColorArr[3])); //设置文字颜色
        imagettftext($this -> _Img,$this -> FontSize,0,$X,$Y,$Color,__WEBROOT__.$this -> Font,$this -> Content); //写入内容
    }

    /**
     * 向图像中写入验证码
     */
    protected function _Write_Code(){
        $_X = $this -> Width / $this -> Codes; //设置宽高比
        for($i = 0;$i < $this -> Codes;$i++){ //循环Codes次,每次生成一位验证码值
            $Color = imagecolorallocate($this -> _Img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156)); //随机生成验证码值的颜色
            imagettftext($this -> _Img,$this -> FontSize,mt_rand(-30,30),$_X*$i+mt_rand(1,5),$this -> Height / 1.3,$Color,__WEBROOT__.$this -> Font,$this -> _Code[$i]); //生成一位验证码值
        }
    }

    /**
     * 向图像中写入干扰线条
     */
    protected function _Write_Line() { //生成干扰线条
        for ($i=0;$i < $this -> Line;$i++) {
            $Color = imagecolorallocate($this -> _Img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
            imageline($this -> _Img,mt_rand(0,$this -> Width),mt_rand(0,$this -> Height),mt_rand(0,$this -> Width),mt_rand(0,$this -> Height),$Color);
        }
    }

    /**
     * 设置图像类型为JPEG
     */
    protected function _Img_Jpeg(){
        header('Content-type:image/jpeg');
        imagejpeg($this -> _Img);
        imagedestroy($this -> _Img);
    }

    /**
     * 设置图像类型为PNG
     */
    protected function _Img_Png(){
        header('Content-type:image/png');
        imagepng($this -> _Img);
        imagedestroy($this -> _Img);
    }

    /**
     * 创建JPEG的字符串图像
     */
    public function Create_Img_Jpg(){
        $this -> _Create_Img_GB(True);
        $this -> _Write_Text();
        $this -> _Img_Jpeg();
    }

    /**
     * 创建PNG的字符串图像
     */
    public function Create_Img_Png(){
        $this -> _Create_Img_GB(True);
        $this -> _Write_Text();
        $this -> _Img_Png();
    }

    /**
     * 创建验证码的PNG图像
     */
    public function Create_Verify(){
        $this -> BackgroundColor = '';
        for($I = 0;$I < 3;$I++){
            $this -> BackgroundColor .= dechex(mt_rand(20,155));
        }
        $this -> _Create_Img_GB(True);
        $this -> _Create_Code();
        $this -> _Write_Line();
        $this -> _Write_Code();
        $this -> _Img_Png();
    }

    /**
     * 外部获取MD5加密后的验证码
     * @return string
     */
    public function Get_Verify(){
        return md5($this -> _Code);
    }

    /**
     * 加载一个图像文件,并获取图像相关信息
     * @param string $FilePath 图像相对路径地址
     * @return $this|bool 成功返回对象,否则返回FALSE
     */
    public function Load_Img($FilePath){
        $FilePath = "D:/phpStudy2016/WWW/lisence/source/3.png";
        if(!is_file($FilePath)){
            $this -> LoadErr = "路径错误,文件不存在";
            Return False;
        }
        $this -> _PicInfo = getimagesize($FilePath);
        $this -> _FileInfo = pathinfo($FilePath);
        switch($this -> _PicInfo[2]){
            case 1:$this ->_FileImg = imagecreatefromgif($FilePath);break;
            case 2:$this ->_FileImg = imagecreatefromjpeg($FilePath);break;
            case 3:$this ->_FileImg = imagecreatefrompng($FilePath);break;
            default:$this -> LoadErr = "类型错误,不支持的图片类型";Return False;
        }
        Return True;
    }

    /**
     * 创建缩略图
     * @param string $FileName 保存的图片名称前缀
     * @param string $FilePath 保存图片的相对路径
     * @return mixed 返回生成的图片的信息数组
     */

    public function Create_Thumb($FileName,$FilePath){
        $SavePath = 'D:/phpStudy2016/WWW/lisence/source/';
        if(!file_exists($SavePath)){
            mkdir($SavePath,0777,true);
        }
        $FileName = $FileName.date("YmdHis").rand(100,999).'.'.$this -> _FileInfo['extension'];
        $FilePath = $FilePath.$FileName;
        $SavePath = $SavePath.$FileName;
        $this -> _Create_Img_GB(False);
        imagecopyresampled($this -> _Img,$this -> _FileImg,0,0,0,0,$this -> Width,$this -> Height,$this -> _PicInfo[0],$this -> _PicInfo[1]);
        switch($this -> _PicInfo[2]){
            case 1:imagegif($this -> _Img,$SavePath);break;
            case 2:imagejpeg($this -> _Img,$SavePath);break;
            case 3:imagepng($this -> _Img,$SavePath);break;
        }
        $FIleInfo['FileName'] = $FileName;
        $FIleInfo['FilePath'] = $FilePath;
        Return $FIleInfo;
    }
}

$img=new Img();
echo $img->Load_Img('D:/phpStudy2016/WWW/lisence/source/3.png');
$img->Create_Thumb('34.png','D:/phpStudy2016/WWW/lisence/source/');

$img->Create_Verify();
弹窗、跳转
<?php   
class view{

        /**
         * 弹窗
         * @param string $_info
         * @return js
         */
        static public function alert($_info) {
            echo "<script type='text/javascript'>alert('$_info');</script>";
            exit();
        }
            /**
         * 弹窗关闭 页面
         * @param string $_info
         * @return js
         */
        static public function alertClose($_info) {
            echo "<script type='text/javascript'>alert('$_info');close();</script>";
            exit();
        }
        /**
         * 页面跳转
         * @param string $url
         * @return js
         */
        static public function headerUrl($url) {
            echo "<script type='text/javascript'>location.href='{$url}';</script>";
            exit();
        }
                    /**
         * js 弹窗并且跳转
         * @param string $_info
         * @param string $_url
         * @return js
         */
        static public function alertLocation($_info, $_url) {
            echo "<script type='text/javascript'>alert('$_info');location.href='$_url';</script>";
            exit();
        }

        /**
         * js 弹窗返回
         * @param string $_info
         * @return js
         */
        static public function alertBack($_info) {
            echo "<script type='text/javascript'>alert('$_info');history.back();</script>";
            exit();
        }
        //搜索并高亮显示关键字
        static function highlighter_text($text, $words){
          $split_words = explode( " " , $words );
          foreach($split_words as $word)
          {
            $color = "#4285F4";
            $text = preg_replace("|($word)|Ui" ,
              "<span style=\"color:".$color.";\"><b>$1</b></span>" , $text );
          }
          return $text;
        }



}
view::alertClose(123);
上传、下载
<?PHP

class updown{
    static public function downFile($file_path) {
            //判断文件是否存在
            $file_path = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码
            if (!file_exists($file_path)) {
                exit('文件不存在!');
            }
            $file_name = basename($file_path); //获取文件名称
            $file_size = filesize($file_path); //获取文件大小
            $fp = fopen($file_path, 'r'); //以只读的方式打开文件
            header("Content-type: application/octet-stream");
            header("Accept-Ranges: bytes");
            header("Accept-Length: {$file_size}");
            header("Content-Disposition: attachment;filename={$file_name}");
            $buffer = 1024;
            $file_count = 0;
            //判断文件是否结束
            while (!feof($fp) && ($file_size-$file_count>0)) {
                $file_data = fread($fp, $buffer);
                $file_count += $buffer;
                echo $file_data;
            }
            fclose($fp); //关闭文件
        }   
    /**
     * 下载远程图片
     * @param string $url 图片的绝对url
     * @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名
     * @param string $filename 要保存的文件名(不含扩展名)
     * @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false
     */
    static public function downloadImage($url, $filepath, $filename) {
        //服务器返回的头信息
        $responseHeaders = array();
        //原始图片名
        $originalfilename = '';
        //图片的后缀名
        $ext = '';
        $ch = curl_init($url);
        //设置curl_exec返回的值包含Http头
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //设置curl_exec返回的值包含Http内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //设置抓取跳转(http 301,302)后的页面
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        //设置最多的HTTP重定向的数量
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);

        //服务器返回的数据(包括http头信息和内容)
        $html = curl_exec($ch);
        //获取此次抓取的相关信息
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        if ($html !== false) {
            //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串
            $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
            //倒数第二段是服务器最后一次response的http头
            $header = $httpArr[count($httpArr) - 2];
            //倒数第一段是服务器最后一次response的内容
            $body = $httpArr[count($httpArr) - 1];
            $header.="\r\n";

            //获取最后一次response的header信息
            preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
            if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {
                for ($i = 0; $i < count($matches[1]); $i++) {
                    if (array_key_exists($i, $matches[2])) {
                        $responseHeaders[$matches[1][$i]] = $matches[2][$i];
                    }
                }
            }
            //获取图片后缀名
            if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
                $originalfilename = $matches[0];
                $ext = $matches[1];
            } else {
                if (array_key_exists('Content-Type', $responseHeaders)) {
                    if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
                        $ext = $extmatches[1];
                    }
                }
            }
            //保存文件
            if (!empty($ext)) {
                //如果目录不存在,则先要创建目录
                if(!is_dir($filepath)){
                    mkdir($filepath, 0777, true);
                }

                $filepath .= '/'.$filename.".$ext";
                $local_file = fopen($filepath, 'w');
                if (false !== $local_file) {
                    if (false !== fwrite($local_file, $body)) {
                        fclose($local_file);
                        $sizeinfo = getimagesize($filepath);
                        return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, 

PATHINFO_BASENAME));
                    }
                }
            }
        }
        return false;
    }

//PHP文件下载头部输出如何设定
static function headerdown(){
$file_download_name="fffff";
header("Content-type: application/x-download");
header("Content-Disposition: attachment; filename=$file_download_name;");
header("Accept-Ranges: bytes");
header("Content-Length: $download_size");
echo "xxx";
}
//PHP用header输出ftp下载方式,并且支持断点续传
static function headerftp(){
    header("Pragma: public");
header("Cache-Control: private");
header("Cache-Control: no-cache, must-revalidate");
header("Accept-Ranges: bytes");
header("Connection: close");
header("Content-Type: audio/mpeg");
header("Location:ftp://download:1bk3l4s3k9s2@232.2.22.22/2222/web技术开发知识库/cn_web.rmvb");

}
}
updown::headerftp();
判断字符编码
class helper{


    /**
     * 判断字符串是utf-8 还是gb2312
     * @param unknown $str
     * @param string $default
     * @return string
     */
    public static function utf8_gb2312($str, $default = 'gb2312')
    {
        $str = preg_replace("/[\x01-\x7F]+/", "", $str);
        if (empty($str)) return $default;
        $preg =  array(
            "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312
            "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u",      //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
        );
        if ($default == 'gb2312') {
            $option = 'utf-8';
        } else {
            $option = 'gb2312';
        }
        if (!preg_match($preg[$default], $str)) {
            return $option;
        }
        $str = @iconv($default, $option, $str);
        //不能转成 $option, 说明原来的不是 $default
        if (empty($str)) {
            return $option;
        }
        return $default;
    }

}
获取ip
    class system{
        //真实ip
        static function realIp() {
            static $realip = NULL;
            if ($realip !== NULL) return $realip;
            if (isset($_SERVER)) {
                if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                    foreach ($arr AS $ip) {
                        $ip = trim($ip);
                        if ($ip != 'unknown') {
                            $realip = $ip;
                            break;
                        }
                    }
                } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                    $realip = $_SERVER['HTTP_CLIENT_IP'];
                } else {
                    if (isset($_SERVER['REMOTE_ADDR'])) {
                        $realip = $_SERVER['REMOTE_ADDR'];
                    } else {
                        $realip = '0.0.0.0';
                    }
                }
            } else {
                if (getenv('HTTP_X_FORWARDED_FOR')) {
                    $realip = getenv('HTTP_X_FORWARDED_FOR');
                } elseif (getenv('HTTP_CLIENT_IP')) {
                    $realip = getenv('HTTP_CLIENT_IP');
                } else {
                    $realip = getenv('REMOTE_ADDR');
                }
            }
            preg_match('/[\d\.]{7,15}/', $realip, $onlineip);
            $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
            return $realip;
        }       
获取操作系统
        if(PATH_SEPARATOR == ':'){
            return 'Linux';
        }else{
            return 'Windows';
        }
    }
    /**
     * 判断当前服务器系统
     * @return string
     */
    public static function getOS(){
        if(PATH_SEPARATOR == ':'){
            return 'Linux';
        }else{
            return 'Windows';
        }
    }
    }
echo system::getOS();
验证登陆
class safe{ /** * 查找ip是否在某个段位里面 * @param string $ip 要查询的ip * @param $arrIP 禁止的ip * @return boolean */ public static function ipAccess($ip='0.0.0.0', $arrIP = array()){ $access = true; $ip && $arr_cur_ip = explode('.', $ip); foreach((array)$arrIP as $key=> $value){ if($value == '*.*.*.*'){ $access = false; //禁止所有 break; } $tmp_arr = explode('.', $value); if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) { //前两段相同 if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){ //第三段为* 或者相同 if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){ //第四段为* 或者相同 $access = false; //在禁止ip列,则禁止访问 break; } } } } return $access; } /** * @param string $string 原文或者密文 * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE * @param string $key 密钥 * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文 * * @example * * $a = authcode('abc', 'ENCODE', 'key'); * $b = authcode($a, 'DECODE', 'key'); // $b(abc) * * $a = authcode('abc', 'ENCODE', 'key', 3600); * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空 */ public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) { $ckey_length = 4; // 随机密钥长度 取值 0-32; // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。 // 取值越大,密文变动规律越大,密文变化 = 16$ckey_length 次方 // 当此值为 0 时,则不产生随机密钥 $key = md5 ( $key ? $key : 'key' ); //这里可以填写默认key值 $keya = md5 ( substr ( $key, 0, 16 ) ); $keyb = md5 ( substr ( $key, 16, 16 ) ); $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : ''; $cryptkey = $keya . md5 ( $keya . $keyc ); $key_length = strlen ( $cryptkey ); $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string; $string_length = strlen ( $string ); $result = ''; $box = range ( 0, 255 ); $rndkey = array (); for($i = 0; $i <= 255; $i ++) { $rndkey [$i] = ord ( $cryptkey [$i % $key_length] ); } for($j = $i = 0; $i < 256; $i ++) { $j = ($j + $box [$i] + $rndkey [$i]) % 256; $tmp = $box [$i]; $box [$i] = $box [$j]; $box [$j] = $tmp; } for($a = $j = $i = 0; $i < $string_length; $i ++) { $a = ($a + 1) % 256; $j = ($j + $box [$a]) % 256; $tmp = $box [$a]; $box [$a] = $box [$j]; $box [$j] = $tmp; $result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) ); } if ($operation == 'DECODE') { if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) { return substr ( $result, 26 ); } else { return ''; } } else { return $keyc . str_replace ( '=', '', base64_encode ( $result ) ); } } /** * 验证登陆 */ public static function validateLogin() { if (empty($_SESSION['admin']['user'])) header('Location:/admin/'); } //普通加密方法 public static function jiami (){ //单向不可反解的密码 $md5=md5("1232"); //单向加密 加干扰值后就固定了。不加干扰值每次都随机 $crypt = crypt ( "字符串", "干扰值"); $Sha1=Sha1(); //用于网络传输 可双向解密的方法 urlencode($str); urldecode($encodestr); //用于网络传输 或编码图片 可双向加密解密的方法 base64_encode($data); base64_decode($data); } //防注入字符串 static function clean($input) { if (is_array($input)) { foreach ($input as $key => $val) { $output[$key] = clean($val); // $output[$key] = $this->clean($val); } } else { $output = (string) $input; // if magic quotes is on then use strip slashes if (get_magic_quotes_gpc()) { $output = stripslashes($output); } // $output = strip_tags($output); $output = htmlentities($output, ENT_QUOTES, 'UTF-8'); } // return the clean text return $output; } }
生成短网址
static function get_tiny_url($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url=' . $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); return $data; }
发送email
    static function send_mail($to, $subject, $body) {
        $headers = "From: KOONK\r\n";
        $headers .= "Reply-To: blog@koonk.com\r\n";
        $headers .= "Return-Path: blog@koonk.com\r\n";
        $headers .= "X-Mailer: PHP5\n";
        $headers .= 'MIME-Version: 1.0' . "\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        mail($to, $subject, $body, $headers);
    }
清理session
    static public function unSession() {
        if (session_start()) {
            session_destroy();
        }
    }
socket方式发送http
    static function socket() {
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        //socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>20, "usec"=>0));
        socket_connect($socket, 'www.baidu.com', 80);
        //里面的换行代表 \r\n 注意拷贝的代码后面可能有空格
        $http = <<<eof
GET / HTTP/1.0
Accept: */*
User-Agent: Lowell-Agent
Host: www.baidu.com
Connection: Close
eof;

        socket_write($socket, $http, strlen($http));
        while ($str = socket_read($socket, 1024)) {
            echo $str;
        }
        socket_close($socket);

    }
fsocketopen 方式发送http
static function fsocketopen(){
    $fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);
    if (!$fp) {
      echo "$errstr ($errno)<br />\n";
    } else {
      $out = "GET / HTTP/1.1\r\n";
      $out .= "Host: www.baidu.com\r\n";
      $out .= "Connection: Close\r\n\r\n";
      fwrite($fp, $http);
      while (!feof($fp)) {
        echo fgets($fp, 128);
      }
      fclose($fp);
    }
    }
原始socket方式
    static function oringsocket(){
        $fp = stream_socket_client("tcp://www.baidu.com:80", $errno, $errstr, 30);
if (!$fp) {
  echo "$errstr ($errno)<br />\n";
} else {
  $http = <<<eof
GET / HTTP/1.0
Accept: */*
User-Agent: Lowell-Agent
Host: www.baidu.com
Connection: Close
eof;
  fwrite($fp, $http);
  while (!feof($fp)) {
    echo fgets($fp, 1024);
  }
  fclose($fp);
}


    }
treampost
static function httpstreampost(){
        $http = <<<eof
Host: www.baidu.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Cookie: BAIDUID=79D98B1AD8436C57B967E111E484F1CD:FG=1; BDUSS=lF-UFFOanFPVG92NmF4U3NiTEoxOFh4YVBCTnZaMUtoTUNhZmxrWThwN25IaUJVQVFBQUFBJCQAAAAAAAAAAAEAAADzo1gKc2lxaW5pYW8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOeR-FPnkfhTU; BAIDUPSID=79D98B1AD8436C57B967E111E484F1CD; BD_UPN=13314352; BD_HOME=1; H_PS_PSSID=10047_1435_10874_10212_10501_10496_10753_10796_10219_10355_10666_10597_10095_10658_10442_10700_10460_10360_10618; sug=3; sugstore=0; ORIGIN=2; bdime=0
Connection: keep-alive
Cache-Control: max-age=0
eof;
$hdrs = array(
    'http' =>array(
        'header' => $http,
        'timeout'=>1, //超时 秒
        'method' => 'GET', //默认方式
         'protocol_version' => '1.1', //默认为 1.0
    ),
);
//参数格式参考 http://php.net/manual/zh/context.http.php
//curl方式的格式可以参考; http://php.net/manual/zh/context.curl.php
$context = stream_context_create($hdrs);
echo file_get_contents('http://www.baidu.com', 0, $context);



    }
ocket tcp udp通信
/*
 * socket tcp udp通信
 * 注意
 * 1.在socket_bind的时候ip地址不能真回环地址如127.0.0.1
 * 2.server.php后台跑起来的时候nohup php server.php > /var/tmp/a.log 2>&1 &
 * */
//udp server
static function udpsocketserver(){
//error_reporting( E_ALL );
set_time_limit( 0 );
ob_implicit_flush();
$socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
if ( $socket === false ) {
  echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "\n";
}
$ok = socket_bind( $socket, '202.85.218.133', 11109 );
if ( $ok === false ) {
  echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) );
}
while ( true ) {
  $from = "";
  $port = 0;
  socket_recvfrom( $socket, $buf,1024, 0, $from, $port );
  echo $buf;
  usleep( 1000 );
}


}
udp client
static function udpsocketclient(){ $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); $msg = 'hello'; $len = strlen($msg); socket_sendto($sock, $msg, $len, 0, '202.85.218.133', 11109); socket_close($sock); }
tcp server
static function tcpsocketserver(){ //error_reporting( E_ALL ); set_time_limit( 0 ); ob_implicit_flush(); $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ); socket_bind( $socket, '192.168.2.143', 11109 ); socket_listen($socket); $acpt=socket_accept($socket); echo "Acpt!\n"; while ( $acpt ) { $words=fgets(STDIN); socket_write($acpt,$words); $hear=socket_read($acpt,1024); echo $hear; if("bye\r\n"==$hear){ socket_shutdown($acpt); break; } usleep( 1000 ); } socket_close($socket); }
tcp client
static function udpsocketclient(){ $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $con=socket_connect($socket,'192.168.2.143',11109); if(!$con){socket_close($socket);exit;} echo "Link\n"; while($con){ $hear=socket_read($socket,1024); echo $hear; $words=fgets(STDIN); socket_write($socket,$words); if($words=="bye\r\n"){break;} } socket_shutdown($socket); socket_close($sock); }
验证登陆
    class yanzheng{
static public function validateLogin() {
            if (empty($_SESSION['admin']['user'])) header('Location:/admin/');
        }
    /**
         * 验证ID  使用系统报错提示
         * @param Number $id
         * @return JS
         */
        static function validateId($id) {
            if (empty($id) || !is_numeric($id)) self::alertBack('警告:参数错误!');
        }
            /**
         * 验证是否相同
         * @param string $str1
         * @param string $str2
         * @param string $alert
         * @return JS
         */
        static function validateAll($str1, $str2, $alert) {
            if ($str1 != $str2) self::alertBack('警告:' .$alert);
        }
    }
yanzheng::validateAll("nj",'asdf','asdf');
文件io操作
class file {
    /**
     * 创建目录
     * @param string $dir
     */
    static public function createDir($dir) {
        if (!is_dir($dir)) {
            mkdir($dir, 0777);
        }
    }

    /**
     * 创建文件(默认为空)
     * @param unknown_type $filename
     */
    static public function createFile($filename) {
        if (!is_file($filename))
            touch($filename);
    }

    /**
     * 删除文件
     * @param string $filename
     */
    static public function delFile($filename) {
        if (file_exists($filename))
            unlink($filename);
    }

    /**
     * 删除目录  必须空目录
     * @param string $path
     */
    static public function delDir($path) {
        if (is_dir($path))
            rmdir($path);
    }

    /**
     * 删除目录及地下的全部文件
     * @param string $dir
     * @return bool
     */
    static public function delDirOfAll($dir) {

        //先删除目录下的文件:
        if (is_dir($dir)) {
            $dh = opendir($dir);
            while (!!$file = readdir($dh)) {
                if ($file != "." && $file != "..") {
                    $fullpath = $dir . "/" . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        self::delDirOfAll($fullpath);
                    }
                }
            }
            closedir($dh);
            //删除当前文件夹:
            if (rmdir($dir)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 遍历文件夹
     * @param string $dir 树形显示
     * @param boolean $all  true表示递归遍历
     * @return array
     */
    public static function scanfDir($dir='', $all = false, &$ret = array()){
        if ( false !== ($handle = opendir ( $dir ))) {
            while ( false !== ($file = readdir ( $handle )) ) {
                if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {
                    $cur_path = $dir . '/' . $file;
                    if (is_dir ( $cur_path )) {
                        $ret['dirs'][] =$cur_path;
                        $all && self::scanfDir( $cur_path, $all, $ret);
                    } else {
                        $ret ['files'] [] = $cur_path;
                    }
                }
            }
            closedir ( $handle );
        }
        return $ret;
    }

    /**
     * 取得输入目录所包含的所有目录和文件
     * 以关联数组形式返回
     * author: flynetcn
     */
    static public function deepScanDir($dir)
    {
        $fileArr = array();
        $dirArr = array();
        $dir = rtrim($dir, '//');
        if(is_dir($dir)){
            $dirHandle = opendir($dir);
            while(false !== ($fileName = readdir($dirHandle))){
                $subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
                if(is_file($subFile)){
                    $fileArr[] = $subFile;
                } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){
                    $dirArr[] = $subFile;
                    $arr = self::deepScanDir($subFile);
                    $dirArr = array_merge($dirArr, $arr['dir']);
                    $fileArr = array_merge($fileArr, $arr['file']);
                }
            }
            closedir($dirHandle);
        }
        return array('dir'=>$dirArr, 'file'=>$fileArr);
    }
/**
     * 取得输入目录所包含的所有文件
     * 以数组形式返回
     * author: flynetcn
     */
    static public function get_dir_files($dir)
    {
        if (is_file($dir)) {
            return array($dir);
        }
        $files = array();
        if (is_dir($dir) && ($dir_p = opendir($dir))) {
            $ds = DIRECTORY_SEPARATOR;
            while (($filename = readdir($dir_p)) !== false) {
                if ($filename=='.' || $filename=='..') { continue; }
                $filetype = filetype($dir.$ds.$filename);
                if ($filetype == 'dir') {
                    $files = array_merge($files, self::get_dir_files($dir.$ds.$filename));
                } elseif ($filetype == 'file') {
                    $files[] = $dir.$ds.$filename;
                }
            }
            closedir($dir_p);
        }
        return $files;
    }
/**
     * 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数)
     * @param string $file 文件/目录
     * @return boolean
     */
    public static function is_writeable($file) {
        if (is_dir($file)){
            $dir = $file;
            if ($fp = @fopen("$dir/test.txt", 'w')) {
                @fclose($fp);
                @unlink("$dir/test.txt");
                $writeable = 1;
            } else {
                $writeable = 0;
            }
        } else {
            if ($fp = @fopen($file, 'a+')) {
                @fclose($fp);
                $writeable = 1;
            } else {
                $writeable = 0;
            }
        }

        return $writeable;
    }

//文件读取函式
static function PHP_Read($file_name) {
$fd=fopen($file_name,'r');
while($bufline=fgets($fd, 4096)){
$buf.=$bufline;
}
fclose($fd);
return $buf;
}

//文件写入函式
static function PHP_Write($file_name,$data,$method=”w”) {
$filenum=@fopen($file_name,$method);
flock($filenum,LOCK_EX);
$file_data=fwrite($filenum,$data);
fclose($filenum);
return $file_data;
}


}

$f=file::PHP_Read("D:/phpStudy2016/WWW/lisence/source/2.txt");

file::PHP_Write("D:/phpStudy2016/WWW/lisence/source/2.txt",$f);
//file::createFile("d:/rfrds1f/ef.jpg");
//file::delDirOfAll("d:/rfrds1f");
GUI
    class gui{
        /**
         * 图片等比例缩放
         * @param resource $im    新建图片资源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif)
         * @param int $maxwidth   生成图像宽
         * @param int $maxheight  生成图像高
         * @param string $name    生成图像名称
         * @param string $filetype文件类型(.jpg/.gif/.png)
         */
        static public function resizeImage($im, $maxwidth, $maxheight, $name, $filetype) {
            $pic_width = imagesx($im);
            $pic_height = imagesy($im);
            if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
                if($maxwidth && $pic_width>$maxwidth) {
                    $widthratio = $maxwidth/$pic_width;
                    $resizewidth_tag = true;
                }
                if($maxheight && $pic_height>$maxheight) {
                    $heightratio = $maxheight/$pic_height;
                    $resizeheight_tag = true;
                }
                if($resizewidth_tag && $resizeheight_tag) {
                    if($widthratio<$heightratio)
                        $ratio = $widthratio;
                    else
                        $ratio = $heightratio;
                }
                if($resizewidth_tag && !$resizeheight_tag)
                    $ratio = $widthratio;
                if($resizeheight_tag && !$resizewidth_tag)
                    $ratio = $heightratio;
                $newwidth = $pic_width * $ratio;
                $newheight = $pic_height * $ratio;
                if(function_exists("imagecopyresampled")) {
                    $newim = imagecreatetruecolor($newwidth,$newheight);
                    imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
                } else {
                    $newim = imagecreate($newwidth,$newheight);
                    imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
                }
                $name = $name.$filetype;
                imagejpeg($newim,$name);
                imagedestroy($newim);
            } else {
                $name = $name.$filetype;
                imagejpeg($im,$name);
            }
        }
/**
         * 给已经存在的图片添加水印
         * @param string $file_path
         * @return bool
         */
        static public function addMark($file_path) {
            if (file_exists($file_path) && file_exists(MARK)) {
                //求出上传图片的名称后缀
                $ext_name = strtolower(substr($file_path, strrpos($file_path, '.'), strlen($file_path)));
                //$new_name='jzy_' . time() . rand(1000,9999) . $ext_name ;
                $store_path = ROOT_PATH . UPDIR;
                //求上传图片高宽
                $imginfo = getimagesize($file_path);
                $width = $imginfo[0];
                $height = $imginfo[1];
                //添加图片水印
                switch($ext_name) {
                    case '.gif':
                        $dst_im = imagecreatefromgif($file_path);
                        break;
                    case '.jpg':
                        $dst_im = imagecreatefromjpeg($file_path);
                        break;
                    case '.png':
                        $dst_im = imagecreatefrompng($file_path);
                        break;
                }
                $src_im = imagecreatefrompng(MARK);
                //求水印图片高宽
                $src_imginfo = getimagesize(MARK);
                $src_width = $src_imginfo[0];
                $src_height = $src_imginfo[1];
                //求出水印图片的实际生成位置
                $src_x = $width - $src_width - 10;
                $src_y = $height - $src_height - 10;
                //新建一个真彩色图像
                $nimage = imagecreatetruecolor($width, $height);
                //拷贝上传图片到真彩图像
                imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height);
                //按坐标位置拷贝水印图片到真彩图像上
                imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height);
                //分情况输出生成后的水印图片
                switch($ext_name) {
                    case '.gif':
                        imagegif($nimage, $file_path);
                        break;
                    case '.jpg':
                        imagejpeg($nimage, $file_path);
                        break;
                    case '.png':
                        imagepng($nimage, $file_path);
                        break;
                }
                //释放资源
                imagedestroy($dst_im);
                imagedestroy($src_im);
                unset($imginfo);
                unset($src_imginfo);
                //移动生成后的图片
                @move_uploaded_file($file_path, ROOT_PATH.UPDIR . $file_path);
            }
        }
//文本转图片
        static function txt2img($str){
        header("Content-type: image/png");
        $string = $str;
        $im = imagecreatefrompng("/5.png");
        $color = imagecolorallocate($im, 255, 255, 255);
        $px = (imagesx($im) - 7.5 * strlen($string)) / 2;
        $py = 9;
        $fontSize = 1;
        imagestring($im, $fontSize, $px, $py, $string, $color);
        imagepng($im);
        imagedestroy($im);
        }


    }

gui::txt2img("asdfasdf");
gui::resizeImage("http://img1.gtimg.com/news/pics/hv1/57/121/2079/135217887.jpg", 200, 200, "ff","jpg");
gui::addMark(@'source/3.png');
时间、数据、格式转化
class data{
    /**
         * 格式化时间
         * @param int $time 时间戳
         * @return string
         */
        static public function formatDate($time='default') {
            $date = $time == 'default' ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $time);
            return $date;
        }       
            /**
         * 格式化字符串  去掉空格和其他字符 只留下相邻字符串
         * @param string $str
         * @return string
         */
        static public function formatStr($str) {
            $arr = array(' ', '	', '&', '@', '#', '%',  '\'', '"', '\\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '=');
            foreach ($arr as $v) {
                $str = str_replace($v, '', $str);
            }
            return $str;
        }
        public static function microtime_float() {
        list ( $usec, $sec ) = explode ( " ", microtime () );
        return (( float ) $usec + ( float ) $sec);
    }
        /**
     * 判断字符串是utf-8 还是gb2312
     * @param unknown $str
     * @param string $default
     * @return string
     */
    public static function utf8_gb2312($str, $default = 'gb2312')
    {
        $str = preg_replace("/[\x01-\x7F]+/", "", $str);
        if (empty($str)) return $default;

        $preg =  array(
            "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312
            "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u",      //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
        );

        if ($default == 'gb2312') {
            $option = 'utf-8';
        } else {
            $option = 'gb2312';
        }

        if (!preg_match($preg[$default], $str)) {
            return $option;
        }
        $str = @iconv($default, $option, $str);

        //不能转成 $option, 说明原来的不是 $default
        if (empty($str)) {
            return $option;
        }
        return $default;
    }
    /**
     * utf-8和gb2312自动转化
     * @param unknown $string
     * @param string $outEncoding
     * @return unknown|string
     */
    public static function safeEncoding($string,$outEncoding = 'UTF-8')
    {
        $encoding = "UTF-8";
        for($i = 0; $i < strlen ( $string ); $i ++) {
            if (ord ( $string {$i} ) < 128)
                continue;

            if ((ord ( $string {$i} ) & 224) == 224) {
                // 第一个字节判断通过
                $char = $string {++ $i};
                if ((ord ( $char ) & 128) == 128) {
                    // 第二个字节判断通过
                    $char = $string {++ $i};
                    if ((ord ( $char ) & 128) == 128) {
                        $encoding = "UTF-8";
                        break;
                    }
                }
            }
            if ((ord ( $string {$i} ) & 192) == 192) {
                // 第一个字节判断通过
                $char = $string {++ $i};
                if ((ord ( $char ) & 128) == 128) {
                    // 第二个字节判断通过
                    $encoding = "GB2312";
                    break;
                }
            }
        }

        if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))
            return $string;
        else
            return @iconv ( $encoding, $outEncoding, $string );
    }


    /**
     * 格式化存储单位
     */
    static public function byteFormat( $size, $dec = 2 ) {
        $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );
        $pos = 0;
        while ( $size >= 1024 ) {
            $size /= 1024;
            $pos ++;
        }
        return round( $size, $dec ) . " " . $a[$pos];
    }
    /*
     * 解析xml
     */
    static function deXML(){        
        $xml_string="<?xml version='1.0'?>
        <moleculedb>
          <molecule name='Benzine'>
            <symbol>ben</symbol>
            <code>A</code>
          </molecule>
          <molecule name='Water'>
            <symbol>h2o</symbol>
            <code>K</code>
          </molecule>
        </moleculedb>";

        //load the xml string using simplexml function
        $xml = simplexml_load_string($xml_string);

        //loop through the each node of molecule
        foreach ($xml->molecule as $record)
        {
          //attribute are accessted by
          echo $record['name'], ' ';
          //node are accessted by -> operator
          echo $record->symbol, ' ';
          echo $record->code, '';
        }       
     }
    /*
     * 解析json
     * */
    static function json(){
        $json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
        $obj=json_decode($json_string);
        //print the parsed data
        echo $obj->name; //displays rolf
        echo $obj->office[0]; //displays google
    }
}
echo data::byteFormat(56456);
curl操作
class curl{
    //多线程下载网页
    public function getweb(){

        $urls = ["asdfas","asdf"]; 
        echo "sdf";
        $save_to='/test.txt'; 
        $st = fopen($save_to,"a"); 
$mh = curl_multi_init(); 
foreach ($urls as $i => $url) { 
$conn[$i] = curl_init($url); 
curl_setopt($conn[$i], CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"); 
curl_setopt($conn[$i], CURLOPT_HEADER ,0); 
curl_setopt($conn[$i], CURLOPT_CONNECTTIMEOUT,60); 
curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,true); // 不将爬取代码写到浏览器,而是转化为字符串 
curl_multi_add_handle ($mh,$conn[$i]); 
} 
do { 
curl_multi_exec($mh,$active); 
} while ($active); 
foreach ($urls as $i => $url) { 
$data = curl_multi_getcontent($conn[$i]); // 获得爬取的代码字符串 
fwrite($st,$data); // 将字符串写入文件
} // 获得数据变量,并写入文件 
foreach ($urls as $i => $url) { 
curl_multi_remove_handle($mh,$conn[$i]); 
curl_close($conn[$i]); 
}
curl_multi_close($mh); 
fclose($st);

    }






        //多线程下载文件
    public static function getfile(){

        $urls=array(
'路径地址5w.zip',
'路径地址5w.zip',
'路径地址5w.zip'
);
$save_to='./home/';
$mh=curl_multi_init();
foreach($urls as $i=>$url){
$g=$save_to.basename($url);
if(!is_file($g)){
$conn[$i]=curl_init($url);
$fp[$i]=fopen($g,"w");
curl_setopt($conn[$i],CURLOPT_USERAGENT,"Mozilla/4.0(compatible; MSIE 7.0; Windows NT 6.0)");
curl_setopt($conn[$i],CURLOPT_FILE,$fp[$i]);
curl_setopt($conn[$i],CURLOPT_HEADER ,0);
curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,60);
curl_multi_add_handle($mh,$conn[$i]);
}
}
do{
$n=curl_multi_exec($mh,$active);
}while($active);
foreach($urls as $i=>$url){
curl_multi_remove_handle($mh,$conn[$i]);
curl_close($conn[$i]);
fclose($fp[$i]);
}
curl_multi_close($mh);$urls=array(
'路径地址5w.zip',
'路径地址5w.zip',
'路径地址5w.zip'
);
$save_to='./home/';
$mh=curl_multi_init();
foreach($urls as $i=>$url){
$g=$save_to.basename($url);
if(!is_file($g)){
$conn[$i]=curl_init($url);
$fp[$i]=fopen($g,"w");
curl_setopt($conn[$i],CURLOPT_USERAGENT,"Mozilla/4.0(compatible; MSIE 7.0; Windows NT 6.0)");
curl_setopt($conn[$i],CURLOPT_FILE,$fp[$i]);
curl_setopt($conn[$i],CURLOPT_HEADER ,0);
curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,60);
curl_multi_add_handle($mh,$conn[$i]);
}
}
do{
$n=curl_multi_exec($mh,$active
}while($active);
foreach($urls as $i=>$url){
curl_multi_remove_handle($mh,$conn[$i]);
curl_close($conn[$i]);
fclose($fp[$i]);
}
curl_multi_close($mh);
    }

//下载网页源文件
function display_sourcecode($url)
{
$lines = file($url);
$output = "";
foreach ($lines as $line_num => $line) {
  // loop thru each line and prepend line numbers
  $output.= "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "\n";
}
}


}

#

#

#

#

#

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千年奇葩

从来没受过打赏,这玩意好吃吗?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值