码迷,mamicode.com
首页 > Web开发 > 详细

简易用的curl类,没看过curl文档也能使用

时间:2015-07-23 13:32:14      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

一切为了简单

 

<?php
/*
 * @content: 对curl进行友好封装
 * @author:wmc
 * @createtime:2015/07/22
 */
/* 功能:
 * 1.获取请求头信息 
 * 2.获取响应头信息
 * 3.获取响应内容
 * 4.获取请求数据
 * 5.能请求 https
 * 6.to be continue
 */
class Curl_Class {
    
    /*
     * curl句柄
     * @access protected
     */
    protected $ch = null;
    
    /*
     * 请求头池
     * @access protected
     */
    protected $headerArr = array();
    
    /*
     * 默认agent
     * @access protected
     */
    protected $defaultAgent = ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36‘;
    
    /*
     * agent 池
     * @access protected
     */
    protected $agentArr = array();
    
    /*
     * 请求ip
     * @access protected
     */
    protected $reqIp = ‘‘;
    
    /*
     * 请求ip池
     * @access protected
     */
    protected  $reqIpArr = array();
    
    /*
     * curl 选项池
     * @access protected
     */
    protected $curlOpt = array();
    
    /*
     * cookie保存文件
     * @access protected
     */
    protected $cookieFile = ‘D:\wamp\www\test\cookie\cookie.txt‘;
    
    /*
     * 状态信息
     * @access public
     */
    public $info = ‘‘;
    
    public function __construct() {
        if(!function_exists(‘curl_init‘)) exit(‘curl扩展库未开启!‘);
        $this->ch = curl_init();
    }
    
    public function __destruct() {
        curl_close($this->ch);
    }
    
    /*
     * 读取url数据
     * @param $url string    请求url
     * @param $data array    请求参数
     * @param $refer boolean 请求来源
     * @param $type string   请求类型
     * @param $timeout int  请求超时时间
     * @return string
     * @throws Exception
     */
    public function readUrl($url, $data=array(), $refer=‘‘, $type=‘get‘, $timeout=3) {
        $url = trim($url);
        if(!$this->isUrl($url)) throw new Exception($this->errMsg(4));
        $type = strtolower($type);
        $rst = false;
        try{
            //判断请求方式
            if($type == ‘get‘) {
                if(!empty($data)) {
                    $url .= (substr($url, -1) == ‘?‘)? http_build_query($data) : ‘?‘ . http_build_query($data);
                }
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, null);  //为GET请求时,去除POSTFIELDS
                curl_setopt($this->ch, CURLOPT_POST, false);       //关闭post请求
                curl_setopt($this->ch, CURLOPT_HTTPGET, true);       //开启GET请求
            } elseif($type == ‘post‘) {
                curl_setopt($this->ch, CURLOPT_HTTPGET, false);      //关闭 get 请求
                curl_setopt($this->ch, CURLOPT_POST, true);          //开启 post 请求
                if(!empty($data)) {
                    curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($data));      //post参数
                }
            }
            
            //cookie文件处理
            if($this->cookieFile == ‘‘) {
                $this->cookieFile = tempnam(‘./cookie‘, ‘cookie‘);
            } elseif(!file_exists($this->cookieFile)) {
                $oldMask = umask(0);
                $fh = fopen($this->cookieFile, ‘w+‘, 0777);
                if($fh == false) throw new Exception($this->errMsg(7));
                fclose($fh);
                umask($oldMask);
            } 
            if(!is_readable($this->cookieFile)) throw new Exception($this->errMsg(8));
            if(!is_writeable($this->cookieFile)) throw new Exception($this->errMsg(9));
            curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookieFile);
            curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookieFile);
            
            //https 处理
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER,false);           // 跳过证书检查  
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, false);           // 从证书中检查SSL加密算法是否存在
            curl_setopt($this->ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );  //强制使用ipv4
            
            //防止内存泄漏,使用代理服务器
            curl_setopt($this->ch, CURLOPT_HTTPPROXYTUNNEL, true);

            //添加头信息
            if(!empty($this->headerArr)) {
                curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->headerArr);
            }
            
            //refer 来源
            if($refer == ‘‘) {
                curl_setopt($this->ch, CURLOPT_AUTOREFERER, true); //当根据Location:重定向时,自动设置header中的Referer:信息。
            } else {
                curl_setopt($this->ch, CURLOPT_REFERER, $refer);
            }
            
            curl_setopt($this->ch, CURLOPT_URL, $url);  //设置url
            curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); //不直接输出返回
            curl_setopt($this->ch, CURLOPT_REFERER, $timeout);    //设置超时时间 
            curl_setopt($this->ch, CURLOPT_USERAGENT, $this->defaultAgent);    //设置浏览器信息
            curl_setopt($this->ch, CURLOPT_FORBID_REUSE, false);  //在完成交互以后强迫断开连接,不能重用。
            curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);  //抓取后是否跳转
            curl_setopt($this->ch, CURLOPT_HEADER, true);  //返回响应头信息
            curl_setopt($this->ch, CURLINFO_HEADER_OUT, true);  //返回请求头信息
            curl_setopt($this->ch, CURLINFO_FILETIME, true);  //返回修改远程文档的信息
            
            //用户自定义选项
            if(!empty($this->curlOpt)) {
                foreach ($this->curlOpt as $key => $value) {
                    if(!defined($key)) throw new Exception($this->errMsg(10) . "($key)");
                    curl_setopt($this->ch, $key, $value);
                }
            }
            $rst = curl_exec($this->ch);
            if(curl_errno($this->ch)) throw new Exception(curl_error($this->ch), curl_errno($this->ch));
            $this->info = curl_getinfo($this->ch);
            $this->info[‘request_params‘] = $data;
            $this->info[‘response_header‘] = substr($rst, 0, $this->info[‘header_size‘]);
            $rst = substr($rst, $this->info[‘header_size‘]);
        }catch (Exception $e) {
            throw new Exception($e->getMessage(), $e->getCode());
        }
        
        return $rst;
    }
    
    /*
     * 用户自定义选项
     * @param $opt array
     */
    public function addOpt($opt) {
        if(empty($opt)) throw new Exception($this->errMsg(5));
        $this->curlOpt = array_merge($this->curlOpt, $opt);
    }
    
    
    /*
     * 添加传送头信息
     * @param $header string | array (string one header)
     * @throws Exception
     */
    public function addHead($header = ‘‘) {
        if(is_string($header)) {
            $header = trim($header);
            if($header == ‘‘) throw new Exception($this->errMsg(1));
            $this->headerArr[] = $header;
        } elseif (is_array($header)) {
            if(empty($header)) throw new Exception($this->errMsg(2));
            $this->headerArr = array_merge($this->headerArr, $header);
        }
    }
    
    /*
     * 添加请求ip
     * @param $ipArr array 
     * @throws Exception
     */
    public function addIp($ipArr) {
        if(!is_array($ipArr) || empty($ipArr)) throw new Exception($this->errMsg(3));
        $this->reqIpArr = array_merge($this->reqIpArr, $ipArr);
    }
    
    /*
     * 出错信息和提示码
     * @param $code int 提示码
     * @return string
     */
    protected function errMsg($code) {
        switch ($code) {
            case 1 :
                    $msg = ‘添加头信息不能为空‘;
                break;
            case 2 :
                    $msg = ‘添加头信息的数据不能为空‘;
                break;
            case 3 :
                    $msg = ‘添加IP的数据必须为数组,且不能为空‘;
                break;
            case 4 :
                    $msg = ‘url格式不正确‘;
                break;
            case 5 :
                    $msg = ‘添加的curl选项值不能为空数组‘;
                break;
            case 6 :
                    $msg = ‘当前cookie保存文件不存在‘;
                break;
            case 7 :
                    $msg = ‘当前cookie文件创建失败‘;
                break;
            case 8 :
                    $msg = ‘当前cookie文件不可读‘;
                break;
            case 9 :
                    $msg = ‘当前cookie文件不可写‘;
                break;
            case 10 :
                    $msg = ‘当前curl配置属性未定义‘;
                break;
            default :
                    $msg = ‘未知错误‘;
                break;
        }
        return $msg;
    }
    
    /*
     * 匹配url是否正确
     * @param $s string
     * @return boolean
     */
    protected function isUrl($s) {
        return preg_match(‘/^http[s]?:\/\/‘.
            ‘(([0-9]{1,3}\.){3}[0-9]{1,3}‘. // IP形式的URL- 199.194.52.184
            ‘|‘. // 允许IP和DOMAIN(域名)
            ‘([0-9a-z_!~*\‘()-]+\.)*‘. // 域名- www.
            ‘([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.‘. // 二级域名
            ‘[a-z]{2,6})‘.  // first level domain- .com or .museum
            ‘(:[0-9]{1,4})?‘.  // 端口- :80
            ‘((\/\?)|‘.  // a slash isn‘t required if there is no file name(\/[0-9a-zA-Z_!~\‘
             \.;\?:@&=\+\$,%#-\/^\*\|]*)?)$/‘,
            $s) == 1;
    }
    
    
    
}

 

简易用的curl类,没看过curl文档也能使用

标签:

原文地址:http://www.cnblogs.com/wumingcong/p/4670136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!