首頁 後端開發 php教程 php http請求curl方法curl http getcurl php curopt httpheade

php http請求curl方法curl http getcurl php curopt httpheade

Jul 29, 2016 am 08:50 AM
curl http

<?php
/**
 * 
 * @brief http请求类
 *
 **/
class Activity_Http
{
    /**
     * Contains the last HTTP status code returned.
     */
    public $http_code;
    /**
     * Contains the last API call.
     */
    public $url;
    /**
     * Set up the API root URL.
     */
    public $host;
    /**
     * Set timeout default.
     */
    public $timeout = 10;
    /**
     * Set connect timeout.
     */
    public $connecttimeout = 10;
    /**
     * Respons format.
     */
    public $format = &#39;unknow&#39;;
    /**
     * Decode returned json data.
     */
    public $decode_json = TRUE;
    /**
     * Contains the last HTTP headers returned.
     */
    public $http_info;
    /**
     * print the debug info
     */
    public $debug = FALSE;
    /**
     * Verify SSL Cert.
     */
    public $ssl_verifypeer = FALSE;
    /**
     * Set the useragnet.
     */
    public $useragent = &#39;xxx&#39;;

    /**
     * 模拟Referer
     * @var url
     */
    public $referer;

    public $follow;

    /**
     * boundary of multipart
     * @ignore
     */
    public static $boundary = &#39;&#39;;

    public function __construct($host = &#39;&#39;)
    {
        $this->host = $host;
    }

    /**
     * GET wrappwer for request.
     *
     * @return mixed
     */
    function get($url, $parameters = array(), $headers = array(),$cookie = array()) {
        $response = $this->request($url, 'GET', $parameters, NULL, $headers,$cookie);
        if ($this->format === 'json' && $this->decode_json) {
            return json_decode($response, true);
        }
        return $response;
    }

    /**
     * POST wreapper for request.
     *
     * @return mixed
     */
    function post($url, $parameters = array(), $multi = false, $headers = array(),$cookie = array()) {
        $response = $this->request($url, 'POST', $parameters, $multi, $headers,$cookie );
        if ($this->format === 'json' && $this->decode_json) {
            return json_decode($response, true);
        }
        return $response;
    }

    /**
     * DELTE wrapper for oAuthReqeust.
     *
     * @return mixed
     */
    function delete($url, $parameters = array()) {
        $response = $this->request($url, 'DELETE', $parameters);
        if ($this->format === 'json' && $this->decode_json) {
            return json_decode($response, true);
        }
        return $response;
    }

    /**
     * Format and sign an OAuth / API request
     *
     * @return string
     * @ignore
     */
    function request($url, $method, $parameters, $multi = false, $headers = array(),$cookie = array()) {

        if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
            $url = "{$this->host}{$url}";
        }

        switch ($method) {
            case 'GET':
                $url .= strpos($url, '?') === false ? '?' : '';
                $url .= http_build_query($parameters);
                return $this->http($url, 'GET', null, $headers, $cookie);
            default:
                //$headers = array();
                $body = $parameters;
                if($multi)
                {
                    $body = self::build_http_query_multi($parameters);
                    $headers[] = "Content-Type: multipart/form-data; boundary=" . self::$boundary;
                }
                elseif(is_array($parameters) || is_object($parameters))
                {
					if(in_array('Content-Type: application/json',$headers) || in_array('Content-Type:application/json',$headers))
					{
						$body = json_encode($parameters);
					}
					else
					{
						$body = http_build_query($parameters);
					}
					
                }

                return $this->http($url, $method, $body, $headers, $cookie);
        }
    }

    /**
     * Make an HTTP request
     *
     * @return string API results
     * @ignore
     */
    function http($url, $method, $postfields = NULL, $headers = array() ,$cookie = array()) {
        $this->http_info = array();
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
        curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_ENCODING, "");
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
        curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
        curl_setopt($ci, CURLOPT_HEADER, FALSE);

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    $this->postdata = $postfields;
                }
                break;
            case 'DELETE':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
                if (!empty($postfields)) {
                    $url = "{$url}?{$postfields}";
                }
        }

        $headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];
        curl_setopt($ci, CURLOPT_URL, $url );
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );
        if($this->referer)
        {
            curl_setopt($ci, CURLOPT_REFERER, $this->referer);
        }
        if ($this->follow)
        {
            curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        }
        
        if(!empty($cookie))
        {
        	$str = "";
        	foreach ($cookie as $key=>$value)
        	{
        		$str.="{$key}={$value};";
        	}
        	
        	$str = trim($str,';');
        	curl_setopt($ci, CURLOPT_COOKIE, $str);
        }

        $response = curl_exec($ci);
        $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
        
        if ($this->http_code != 200)
        {
        	throw new Exception(json_encode($this->http_info), $this->http_code);
        }
        
        
        $this->url = $url;

        curl_close ($ci);
        return $response;
    }

    /**
     * Get the header info to store.
     *
     * @return int
     * @ignore
     */
    function getHeader($ch, $header) {
        $i = strpos($header, ':');
        if (!empty($i)) {
            $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
            $value = trim(substr($header, $i + 2));
            $this->http_header[$key] = $value;
        }
        return strlen($header);
    }

    /**
     * 处理多媒体数据内容
     * @ignore
     */
    public static function build_http_query_multi($params) {
        if (!$params) return '';

        uksort($params, 'strcmp');

        $pairs = array();

        self::$boundary = $boundary = uniqid('------------------');
        $MPboundary = '--'.$boundary;
        $endMPboundary = $MPboundary. '--';
        $multipartbody = '';

        foreach ($params as $parameter => $value) {

            if( in_array($parameter, array('pic', 'image','Filedata')) && $value{0} == '@' ) {
                $url = ltrim( $value, '@' );
                $content = file_get_contents( $url );
                $array = explode( '?', basename( $url ) );
                $filename = $array[0];

                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"'. "\r\n";
                $multipartbody .= "Content-Type: image/unknown\r\n\r\n";
                $multipartbody .= $content. "\r\n";
            } else {
                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
                $multipartbody .= $value."\r\n";
            }

        }

        $multipartbody .= $endMPboundary;
        return $multipartbody;
    }
    
    
 	/**
     * 批量请求urlget
     * Enter description here ...
     * @param unknown_type $urls
     * @return array
     */
    public function batch_get($url_arr)
    {
	    $mh = curl_multi_init();
		foreach ($url_arr as $i => $url) 
		{
		     $conn[$i]=curl_init($url);
		     curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1);//设置返回do.php页面输出内容
		     curl_multi_add_handle ($mh,$conn[$i]);//添加线程
		}
		
		
		do 
		{
		     $mrc = curl_multi_exec($mh,$active);
		} 
		while ($mrc == CURLM_CALL_MULTI_PERFORM);
		while ($active and $mrc == CURLM_OK) 
		{
	         if (curl_multi_select($mh) != -1) {
		         do 
		         {
		         	$mrc = curl_multi_exec($mh, $active);
		         }
		         while($mrc == CURLM_CALL_MULTI_PERFORM);
	         }
		}
		
		foreach ($url_arr as $i => $url) 
		{
			$res[$i]=curl_multi_getcontent($conn[$i]);//得到页面输入内容
			curl_close($conn[$i]);
		}
		return $res;
    }
    
}
登入後複製

以上就介紹了php http請求 curl方法,包括了curl,http方面的內容,希望對PHP教程有興趣的朋友有幫助。

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

http狀態碼520是什麼意思 http狀態碼520是什麼意思 Oct 13, 2023 pm 03:11 PM

http狀態碼520是什麼意思

Linux下更新curl版本教程! Linux下更新curl版本教程! Mar 07, 2024 am 08:30 AM

Linux下更新curl版本教程!

瞭解網頁重定向的常見應用場景並了解HTTP301狀態碼 瞭解網頁重定向的常見應用場景並了解HTTP301狀態碼 Feb 18, 2024 pm 08:41 PM

瞭解網頁重定向的常見應用場景並了解HTTP301狀態碼

如何使用Nginx Proxy Manager實現HTTP到HTTPS的自動跳轉 如何使用Nginx Proxy Manager實現HTTP到HTTPS的自動跳轉 Sep 26, 2023 am 11:19 AM

如何使用Nginx Proxy Manager實現HTTP到HTTPS的自動跳轉

從頭到尾:如何使用php擴充cURL進行HTTP請求 從頭到尾:如何使用php擴充cURL進行HTTP請求 Jul 29, 2023 pm 05:07 PM

從頭到尾:如何使用php擴充cURL進行HTTP請求

http狀態碼403是什麼 http狀態碼403是什麼 Oct 07, 2023 pm 02:04 PM

http狀態碼403是什麼

http請求415錯誤解決方法 http請求415錯誤解決方法 Nov 14, 2023 am 10:49 AM

http請求415錯誤解決方法

PHP Curl中如何處理網頁的 301 重定向? PHP Curl中如何處理網頁的 301 重定向? Mar 08, 2024 am 11:36 AM

PHP Curl中如何處理網頁的 301 重定向?

See all articles