Table of Contents
[PHP]代码   " >[PHP]代码   
Home php教程 PHP源码 curl类封装

curl类封装

May 23, 2016 am 08:39 AM
php

[PHP]代码   

<?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 = "";  //cookie_file路径
	private $cookie_mode = 0;    //cookie保存模式 0不使用 1客户端、2服务器文件
	private $show_header = 0;    //是否输出返回头信息
	private $set_useragent = ""; //模拟用户使用的浏览器,默认为模拟
	
    //构造函数  
    public function __construct($url = ""){  
        $this->ch = curl_init();  
        $this->url = $url ? $url : $this->url;
        //$this->set_useragent = $_SERVER[&#39;HTTP_USER_AGENT&#39;]; // 模拟用户使用的浏览器   
        $this->set_useragent ="Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/7.0 Mobile/10B350 Safari/9537.53";
        // $this->set_useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36";
        //$this->cookie_file=dirname(__FILE__)."/cookie_".md5(basename(__FILE__)).".txt";	//初始化cookie文件路径	
        //$this->cookie_file= SAE_TMP_PATH.TmpFS;
        $this->cookie_file = "saekv://cookie_2014.txt";
    }  
    //关闭curl
    public function close(){  
        curl_close($this->ch);  
    }  
    //析构函数  
    public function __destruct(){  
        $this->close();  
    }  
    
   //设置超时	
    public function set_time_out($timeout=20){  
        if(intval($timeout) != 0)		
		$this->set_time_out = $timeout;
		return $this;
    }  
    //设置来源页面  
    public function set_referer($referer = ""){  
        if (!empty($referer))  
            curl_setopt($this->ch, CURLOPT_REFERER , $referer);  
        return $this;  
    }
    //设置cookie存放模式 1客户端、2服务器文件	
	public function set_cookie_mode($mode = ""){  
	    $this->cookie_mode = $mode;
		return $this;
	}
    //载入cookie  
    public function load_cookie(){  
	
	    if($this->cookie_mode == 1 ) {
		    if(isset($_COOKIE[&#39;curl&#39;])){
		        curl_setopt($this->ch,CURLOPT_COOKIE,$_COOKIE[&#39;curl&#39;]);
		    }else{
			    $this->exec();
			    curl_setopt($this->ch,CURLOPT_COOKIE,$this->cookie_file);
			}
			
		}
		if($this->cookie_mode == 2 ) {
          
            curl_setopt($this->ch, CURLOPT_COOKIEFILE , $this->cookie_file);
            
		}
        if($this->cookie_mode == 3 ) {
            $kv = new SaeKV();
            $ret = $kv->init();
            $ret = $kv->get(&#39;curl_cookie&#39;);
            if($ret)
               curl_setopt($this->ch,CURLOPT_COOKIE, $ret);
            
		}
        return $this;  
    }  
   
	//设置保存cookie方式 $cookie_val 模式1为变量 模式2为文件路径
    public function save_cookie($cookie_val = "") {  
	    //保存在客户端
	    if($this->cookie_mode == 1 && $cookie_val){
		   setcookie(&#39;curl&#39;,$cookie_val); 
		}
		//保存服务器端
		if($this->cookie_mode == 2){ 
            if(!empty($cookie_val))  
               $this->cookie_file =  $cookie_val;
		    curl_setopt($this->ch, CURLOPT_COOKIEJAR , $this->cookie_file);  
		}
        //保存在sae
        if($this->cookie_mode == 3 && $cookie_val){
		     $kv = new SaeKV();
             $ret = $kv->init();
             $ret = $kv->get(&#39;curl_cookie&#39;);
            if($ret){
                $ret = $kv->set(&#39;curl_cookie&#39;, $cookie_val );
                
            }else{
                 $ret = $kv->add(&#39;curl_cookie&#39;, $cookie_val);
            
            }
		}
        
        
        return $this;  
		
    }  
    //post参数 (array) $post 
    public function post ($post = ""){  
	    if($post && is_array($post)){
            curl_setopt($this->ch, CURLOPT_POST , 1);  
            curl_setopt($this->ch, CURLOPT_POSTFIELDS , $post );  
		}
        return $this;  
    }  
    //设置代理 ,例如&#39;68.119.83.81:27977&#39;  
    public function set_proxy($proxy = ""){
        if($proxy){	
            curl_setopt($this->ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);  
            curl_setopt($this->ch, CURLOPT_PROXY,$proxy); 
        }			
        return $this;  
    }  
    //设置伪造ip  
    public function set_ip($ip=""){  
        if(!empty($ip))  
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, array("X-FORWARDED-FOR:$ip", "CLIENT-IP:$ip"));  
        return $ip;  
    } 
     //设置是否显示返回头信息
    public function show_header($show=0){
        $this->show_header = 0; 	
        if($show) 
            $this->show_header = 1; 
        return $this;  
    }

     //设置请求头信息
    public function set_useragent($str=""){  
        if($str)  
            $this->set_useragent = $str;  
		return $this;  
    } 	
	
	//执行  
    public function exec ($url = ""){  
	    if(!$url) $url = $this->url;
	    curl_setopt($this->ch, CURLOPT_URL, $url); // 要访问的地址
	    curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查   
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER , 1 );    //获取的信息以文件流的形式返回		
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在 
         curl_setopt($this->ch, CURLOPT_USERAGENT, $this->set_useragent); // 模拟用户使用的浏览器      
        curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转      
        curl_setopt($this->ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer 
	    curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->set_time_out);  //超时设置
		curl_setopt($this->ch, CURLOPT_HEADER, $this->show_header); // 显示返回的Header区域内容
		curl_setopt($this->ch, CURLOPT_NOBODY, 0);//不返回response body内容 
		
        $res = curl_exec($this->ch);
		$this->flag_if_have_run = true;
        if (curl_errno($this->ch)) {      
            //echo &#39;Errno&#39;.curl_error($this->ch);  
            return false;			
        } 
        if($this->show_header == 1){ //数组形式返回头信息和body信息 
		    list($header, $body) = explode("\r\n\r\n", $res);
			$arr[&#39;header&#39;] = $header;
			$arr[&#39;body&#39;] = $body;
			if($this->cookie_mode == 1 || $this->cookie_mode == 3){  
				preg_match_all("/set\-cookie:([^\r\n]*)/i", $header, $matches);
                //print_r($matches);
				if($matches && isset($matches[1]) ){
				    $val = implode(&#39;;&#39;,array_unique(explode(&#39;;&#39;,implode(&#39;;&#39;,$matches[1])))); //去重处理
					if($val)
					  $this->save_cookie($val); //设置客户端保存cookie
				}
			}
			if($arr) return $arr;
		}
		
		return $res;  
    }  
	
	
    //返回  curl_getinfo信息
    public function get_info(){  
        if($this->flag_if_have_run == true )  
            return curl_getinfo($this->ch);  
        else   
            throw new Exception("<h1>需先运行( 执行exec ),再获取信息</h1>");  
    }  
	 
}  
?>
Copy after login

                   

                   

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles