好用的curl类

 <?php
 /*使用方法
$ch = new Curl_Class();
$ch->set_action("login", $loginurl, $refer);
$postdata = array("username"=>"fortest", "password"=>"12345");
$ch->open()->get_cookie($this->_cookie)->get("login", $postdata);
$result = $ch->header() . $ch->body();
$ch->close();*/
//curl类源码
class Curl_Class
{
    private $_is_temp_cookie = false;
    private $_header;
    private $_body;
    private $_ch;

    private $_proxy;
    private $_proxy_port;
    private $_proxy_type = ‘HTTP‘; // or SOCKS5
    private $_proxy_auth = ‘BASIC‘; // or NTLM
    private $_proxy_user;
    private $_proxy_pass;

    protected $_cookie;
    protected $_options;
    protected $_url = array ();
    protected $_referer = array ();

    public function __construct($options = array()) {
        $defaults = array ();

        $defaults [‘timeout‘] = 30;
        $defaults [‘temp_root‘] = sys_get_temp_dir ();
        $defaults [‘user_agent‘] = ‘Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20‘;

        $this->_options = array_merge ( $defaults, $options );
    }

    public function open() {
        $this->_ch = curl_init ();

        //curl_setopt ( $this->_ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt ( $this->_ch, CURLOPT_HEADER, true );
        curl_setopt ( $this->_ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt ( $this->_ch, CURLOPT_USERAGENT, $this->_options [‘user_agent‘] );
        curl_setopt ( $this->_ch, CURLOPT_CONNECTTIMEOUT, $this->_options [‘timeout‘] );
        curl_setopt ( $this->_ch, CURLOPT_HTTPHEADER, array(‘Expect:‘) ); // for lighttpd 417 Expectation Failed

        $this->_header = ‘‘;
        $this->_body = ‘‘;

        return $this;
    }

    public function close() {
        if (is_resource ( $this->_ch )) {
            curl_close ( $this->_ch );
        }

        if (isset ( $this->_cookie ) && $this->_is_temp_cookie && is_file ( $this->_cookie )) {
            unlink ( $this->_cookie );
        }
    }

    public function cookie() {
        if (! isset ( $this->_cookie )) {
            if (! empty ( $this->_cookie ) && $this->_is_temp_cookie && is_file ( $this->_cookie )) {
                unlink ( $this->_cookie );
            }

            $this->_cookie = tempnam ( $this->_options [‘temp_root‘], ‘curl_manager_cookie_‘ );
            $this->_is_temp_cookie = true;
        }

        curl_setopt ( $this->_ch, CURLOPT_COOKIEJAR, $this->_cookie ); //写cookie
        curl_setopt ( $this->_ch, CURLOPT_COOKIEFILE, $this->_cookie ); //读cookie;

        return $this;
    }

    public function get_cookie($cookfile) {

        curl_setopt ( $this->_ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt ( $this->_ch, CURLOPT_COOKIEJAR, $cookfile );

        return $this;
    }

    public function set_cookie($cookfile) {

        curl_setopt ( $this->_ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt ( $this->_ch, CURLOPT_COOKIEFILE, $cookfile );

        return $this;
    }

    public function set_session($session) { //$session为真或假

        curl_setopt ( $this->_ch, CURLOPT_COOKIESESSION,  $session ); //启用时curl会仅仅传递一个session cookie,忽略其他的cookie,默认状况下cURL会将所有的cookie返回给服务端。session cookie是指那些用来判断服务器端的session是否有效而存在的cookie。

        return $this;
    }

    public function ssl() {
        curl_setopt ( $this->_ch, CURLOPT_SSL_VERIFYPEER, false );

        return $this;
    }

    public function proxy($host = null, $port = null, $type = null, $user = null, $pass = null, $auth = null) {
        $this->_proxy = isset ( $host ) ? $host : $this->_proxy;
        $this->_proxy_port = isset ( $port ) ? $port : $this->_proxy_port;
        $this->_proxy_type = isset ( $type ) ? $type : $this->_proxy_type;

        $this->_proxy_auth = isset ( $auth ) ? $auth : $this->_proxy_auth;
        $this->_proxy_user = isset ( $user ) ? $user : $this->_proxy_user;
        $this->_proxy_pass = isset ( $pass ) ? $pass : $this->_proxy_pass;

        if (! empty ( $this->_proxy )) {
            curl_setopt ( $this->_ch, CURLOPT_PROXYTYPE, $this->_proxy_type == ‘HTTP‘ ? CURLPROXY_HTTP : CURLPROXY_SOCKS5 );
            curl_setopt ( $this->_ch, CURLOPT_PROXY, $this->_proxy );
            curl_setopt ( $this->_ch, CURLOPT_PROXYPORT, $this->_proxy_port );
        }

        if (! empty ( $this->_proxy_user )) {
            curl_setopt ( $this->_ch, CURLOPT_PROXYAUTH, $this->_proxy_auth == ‘BASIC‘ ? CURLAUTH_BASIC : CURLAUTH_NTLM );
            curl_setopt ( $this->_ch, CURLOPT_PROXYUSERPWD, "[{$this->_proxy_user}]:[{$this->_proxy_pass}]" );
        }

        return $this;
    }

    public function post($action, $query = array()) {
       // print_r($query);
        //die;
        if (is_array($query)&& !empty($query)) {
            foreach($query as $key=>&$val){
                //die(‘bb‘);
                if (!empty ($val) && $val{0} != ‘@‘) {
                    $val = urlencode(mb_convert_encoding($val, ‘utf-8‘, ‘gb2312‘));
                }
            }
            $query = http_build_query($query);
//             echo $query;
//             die;
        }else{//多选
        	$query = $query;
        }

        //print_r($this->_url[$action]);
       // die;
        //print_r($query);
        //die;
        curl_setopt ( $this->_ch, CURLOPT_POST, true );
        curl_setopt ( $this->_ch, CURLOPT_URL, $this->_url[$action] );
        curl_setopt ( $this->_ch, CURLOPT_REFERER, $this->_referer[$action] );
        curl_setopt ( $this->_ch, CURLOPT_POSTFIELDS, $query );

        $this->_requrest ();

        return $this;
    }

    public function get($action, $query = array()) {
        $url = $this->_url [$action];

        if (! empty ( $query )) {
            $url .= strpos ( $url, ‘?‘ ) === false ? ‘?‘ : ‘&‘;
            $url .= is_array ( $query ) ? http_build_query ( $query ) : $query;
        }

        curl_setopt ( $this->_ch, CURLOPT_URL, $url );
        curl_setopt ( $this->_ch, CURLOPT_REFERER, $this->_referer [$action] );

        $this->_requrest();

        return $this;
    }

    public function getinfo() {
        return curl_getinfo($this->_ch);
    }
    public function output_trace($output) {
        curl_setopt ( $this->_ch, CURLOPT_VERBOSE,1 );
        curl_setopt ( $this->_ch, CURLOPT_STDERR,$output );

        return $this;
    }

    public function download($action, $query = array(), $saveto, $rewritemode=0) {
        $url = $this->_url [$action];
        if (! empty ( $query )) {
            $url .= strpos ( $url, ‘?‘ ) === false ? ‘?‘ : ‘&‘;
            $url .= is_array ( $query ) ? http_build_query ( $query ) : $query;
        }
        try
        {
            if ($rewritemode==1 || !file_exists($saveto))
            {
                $fp = @fopen($saveto, "wb");
                @curl_setopt ($this->_ch, CURLOPT_FILE, $fp);
                curl_setopt ($this->_ch, CURLOPT_URL, $url );
                curl_setopt ($this->_ch, CURLOPT_HEADER,0);
                curl_setopt ( $this->_ch, CURLOPT_REFERER, $this->_referer [$action] );
                curl_exec ( $this->_ch );

                curl_close($this->_ch);

                @fclose($fp);
            }
            return true;
        }
        catch (exception $e)
        {
            return false;
        }
    }

    public function put($action, $query = array()) {
        curl_setopt ( $this->_ch, CURLOPT_CUSTOMREQUEST, ‘PUT‘ );

        return $this->post( $action, $query );
    }

    public function delete($action, $query = array()) {
        curl_setopt ( $this->_ch, CURLOPT_CUSTOMREQUEST, ‘DELETE‘ );

        return $this->post( $action, $query );
    }

    public function head($action, $query = array()) {
        curl_setopt ( $this->_ch, CURLOPT_CUSTOMREQUEST, ‘HEAD‘ );

        return $this->post( $action, $query );
    }

    public function options($action, $query = array()) {
        curl_setopt ( $this->_ch, CURLOPT_CUSTOMREQUEST, ‘OPTIONS‘ );

        return $this->post( $action, $query );
    }

    public function trace($action, $query = array()) {
        curl_setopt ( $this->_ch, CURLOPT_CUSTOMREQUEST, ‘TRACE‘ );

        return $this->post( $action, $query );
    }

    public function connect() {

    }

    public function follow_location() {
        preg_match ( ‘#Location:\s*(.+)#i‘, $this->header (), $match );

        if (isset ( $match [1] )) {
            $this->set_action( ‘auto_location_gateway‘, $match [1], $this->effective_url () );

            $this->get( ‘auto_location_gateway‘ )->follow_location ();
        }

        return $this;
    }

    public function set_action($action, $url, $referer = ‘‘) {
        $this->_url [$action] = $url;
        $this->_referer [$action] = $referer;

        return $this;
    }

    public function header() {
        return $this->_header;
    }

    public function body() {
        return $this->_body;
    }

    public function effective_url() {
        return curl_getinfo ( $this->_ch, CURLINFO_EFFECTIVE_URL );
    }

    public function http_code() {
        return curl_getinfo($this->_ch, CURLINFO_HTTP_CODE);
    }

    private function _requrest() {
        $response = curl_exec ( $this->_ch );

        $errno = curl_errno ( $this->_ch );

        if ($errno > 0) {
            throw new Curl_Manager_Exception ( curl_error ( $this->_ch ), $errno );
        }

        $header_size = curl_getinfo ( $this->_ch, CURLINFO_HEADER_SIZE );

        $this->_header = substr ( $response, 0, $header_size );
        $this->_body = substr ( $response, $header_size );
    }

    public function __destruct() {
        $this->close ();
    }
}

class Curl_Manager_Exception extends Exception {   

}
时间: 2024-10-28 14:19:15

好用的curl类的相关文章

一个基础的CURL类

/** * 一个基础的CURL类 * * @author Smala */ class curl{ public $ch; public $cookie = '/cookie'; public $rstr; public $info; public function __construct($ssl=true,$cookieName="tmp.cookie"){ $this -> cookie = dirname(__FILE__)."/".$cookieNa

PHP通用CURL类

PHP通用CURL类,可POST/GET/文件传输 function do_curl($url, $params = array(), $upload = false, $type = 'POST') { $method = strtoupper($type); if ($method == 'GET') { $url = "{$url}?" . http_build_query($params); } $ch = curl_init(); // $header[] = "U

一个简单的PHP的CURL类

我写了一个基于CURL的PHP5的类,功能比较简单,比较适合学习用.如果真要应用的话,那绝对推荐Snoopy 太强大了.虽然它不是在curl基础上的.转自 http://xiaowai.gentieba.com/node/33 <?php class my_curl { public function __construct() { ! extension_loaded ( 'curl' ) && exit ( 'CURL扩展未加载,程序终止运行' ); header ( 'Cont

php中curl类常用方法封装和详解

curl对于PHP开发这来说是经常用到的一个类. 在抓取远程文件或是内容的时候就更常用了. 不过原生态的curl类比较复杂, 尤其对于新手来说,很多参数很容易让人头晕,现在好了. 这个类是封装了几个常用的curl函数. 可以实现抓取远程文件,模拟提交数据等功能. /* * 来源: http://www.xuehuwang.com/ * 作者: 雪狐博客 * 类用途: 实现抓取原创内容 */ class CURL { var $cookie_file; // 设置Cookie文件保存路径及文件名

curl类封装

<?php /**   * @author askwei **/   class CURL   {      private $ch;      private $url = "http://www.baidu.com";     private $flag_if_have_run;   //标记exec是否已经运行     private $set_time_out = 20;  //设置curl超时时间     private $cookie_file = "&qu

封装curl类,post get方法实现网站请求

<?phpclass RamDemo{    //get方法    function RamGet($url,$arr)    {        if($arr!=''){            $ar=array();            foreach($arr as $k=>$v){                $ar[]=$k.'='.$v;               }            $url=$url.'?'.implode('&',$ar);       

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

一切为了简单 <?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; /*

使用curl模拟ip和来源进行网站采集的实现方法

对于限制了ip和来源的网站,使用正常的采集方式是不行的.本文将介绍一种方法,使用php的curl类实现模拟ip和来源,实现采集限制ip和来源的网站. 1.设置页面限制ip和来源访问 server.php <?php $client_ip = getip(); $referer = getreferer(); $allow_ip = '192.168.1.100'; $allow_referer = 'http://www.uxuew.cn'; if($client_ip==$allow_ip &am

PHP之curl函数相关试题

一.问答题 1.curl_setopt中超时设置,URL设置,post数据接收设置,解压缩设置,HEADER信息设置的参数名分别是什么? 2.curl批量设置参数的函数是什么? 二.编程题 1.封装一个curl类,提供get,post方法,通过传递url,data数据获取某个网址的内容,方法返回信息格式为array('response'=>'网页内容','status'=>'http请求状态码','error'=>'错误信息') 要求能够改header信息,并且有超时机制,zip解压缩功