PHP cURL詳解,get、put、delete、post等,連貫操作實現(xiàn)

curl是一種在命令行利用URL語法實現(xiàn)文件傳輸?shù)墓ぞ?br> 以下是一些簡單curl功能的連貫操作方式實現(xiàn)
...
<hr />
...

<?php
class Mcurl
{
    public $ch;

    public function __construct()
    {
        $this->ch = curl_init();
    }


    private function init($url)
    {
        //初始化CURL句柄
        curl_setopt($this->ch, CURLOPT_URL, $url);//設(shè)置請求的URL
        // curl_setopt($this->ch, CURLOPT_HEADER, false);// 不要http header 加快效率
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); //設(shè)為TRUE把curl_exec()結(jié)果轉(zhuǎn)化為字串,而不是直接輸出
        
        $header[] = "Content-Type:application/json;charset=utf-8";
        if(! empty($header))
        {
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header);//設(shè)置 HTTP 頭字段的數(shù)組。格式: array('Content-type: text/plain', 'Content-length: 100') 
        }

        return $this;
    }

    /**
     * 如果需要登錄
     * @param  [type] $username [description]
     * @param  [type] $password [description]
     * @return [type]           [description]
     */
    public function auth($username, $password)
    {
        // 傳遞一個連接中需要的用戶名和密碼,格式為:"[username]:[password]"。
        curl_setopt($this->ch, CURLOPT_USERPWD, "{$username}:{$password}");
    }


    public function post(array $params)
    {
        // curl_setopt($this->ch, CURLOPT_POST,true);//TRUE 時會發(fā)送 POST 請求,類型為:application/x-www-form-urlencoded,是 HTML 表單提交時最常見的一種。
        // curl_setopt($this->ch, CURLOPT_NOBODY, true);//TRUE 時將不輸出 BODY 部分。同時 Mehtod 變成了 HEAD。修改為 FALSE 時不會變成 GET。
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "POST");//HTTP 請求時,使用自定義的 Method 來代替"GET"或"HEAD"。對 "DELETE" 或者其他更隱蔽的 HTTP 請求有用。 有效值如 "GET","POST","CONNECT"等等;
        //設(shè)置提交的信息
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));//全部數(shù)據(jù)使用HTTP協(xié)議中的 "POST" 操作來發(fā)送。

        return $this->close();
    }


    public function head()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "HEAD");

        return $this->close();
    }


    public function delete()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "DELETE");

        return $this->close();
    }


    public function put($params = [])
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));

        return $this->close();
    }


    public function get()
    {
        curl_setopt($this->ch, CURLOPT_HTTPGET, true);//TRUE 時會設(shè)置 HTTP 的 method 為 GET,由于默認(rèn)是 GET,所以只有 method 被修改時才需要這個選項。 

        return $this->close();
    }


    /**
     * 執(zhí)行并關(guān)閉
     * @return [type] [description]
     */
    private function close()
    {
        $data = curl_exec($this->ch);//執(zhí)行預(yù)定義的CURL
        $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);//獲取http返回值,最后一個收到的HTTP代碼
        curl_close($this->ch);//關(guān)閉cURL會話
        $res = json_decode($data, true);

        return $res;
    }


    /**
     * 是否是https
     * @return [type] [description]
     */
    public function https()
    {
        //SSL驗證
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https請求時要設(shè)置為false 不驗證證書和hosts  FALSE 禁止 cURL 驗證對等證書(peer's certificate), 自cURL 7.10開始默認(rèn)為 TRUE。從 cURL 7.10開始默認(rèn)綁定安裝。 
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE);//檢查服務(wù)器SSL證書中是否存在一個公用名(common name)。
        
        return $this;
    }


    /**
     * 請求時間
     * @param  integer $timeout [description]
     * @return [type]           [description]
     */
    public function out($timeout = 30)
    {
        //請求時間
        curl_setopt ($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout);//設(shè)置連接等待時間

        return $this;
    }


    public function __call($method, $params)
    {
        if (method_exists($this, $method))
        {
            return $this->$method(...$params);
        }
    }


    public static function __callStatic($method, $params)
    {
        $Mcurl = new Mcurl;

        if (method_exists($Mcurl, $method))
        {
            return $Mcurl->$method(...$params);
        }
    }
}

// $url = 'x';
// $a = Mcurl::init($url)->get();
// print_r($a);

附上已model形式封裝的curl

<?php
namespace App\Model\Base;

class Curl
{
    private $ch;  // curl對象
    public $url;  // 地址
    public $port;  // 端口
    public $route;  // 路由
    public $header = [];  // header
    public $returnTransfer = 1; // 轉(zhuǎn)化字符串
    public $json = true;

    public function __construct()
    {
        if ($this->url)
        {
            $this->setUrl();
            $this->init();
        }
    }

    private function setUrl()
    {
        $this->url = config($this->url);
        $this->port && $this->url .= ':' . config($this->port);
        $this->route && $this->url .= '/' . $this->route;
    }

    /**
     * 自定義url
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
    private function customUrl($url)
    {
        $this->url = $url;
        $this->init();

        return $this;
    }

    private function init()
    {
        $this->ch = curl_init();
        //初始化CURL句柄
        curl_setopt($this->ch, CURLOPT_URL, $this->url);//設(shè)置請求的URL
        // curl_setopt($this->ch, CURLOPT_HEADER, false);// 不要http header 加快效率
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, $this->returnTransfer); //設(shè)為TRUE把curl_exec()結(jié)果轉(zhuǎn)化為字串,而不是直接輸出
        
        $this->header[] = "Content-Type:application/json;charset=utf-8";
        if(! empty($this->header))
        {
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->header);//設(shè)置 HTTP 頭字段的數(shù)組。格式: array('Content-type: text/plain', 'Content-length: 100') 
        }

        return $this;
    }

    /**
     * 如果需要登錄
     * @param  [type] $username [description]
     * @param  [type] $password [description]
     * @return [type]           [description]
     */
    private function auth($username, $password)
    {
        // 傳遞一個連接中需要的用戶名和密碼,格式為:"[username]:[password]"。
        curl_setopt($this->ch, CURLOPT_USERPWD, "{$username}:{$password}");

        return $this;
    }


    private function post($params = [])
    {
        // curl_setopt($this->ch, CURLOPT_POST,true);//TRUE 時會發(fā)送 POST 請求,類型為:application/x-www-form-urlencoded,是 HTML 表單提交時最常見的一種。
        // curl_setopt($this->ch, CURLOPT_NOBODY, true);//TRUE 時將不輸出 BODY 部分。同時 Mehtod 變成了 HEAD。修改為 FALSE 時不會變成 GET。
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "POST");//HTTP 請求時,使用自定義的 Method 來代替"GET"或"HEAD"。對 "DELETE" 或者其他更隱蔽的 HTTP 請求有用。 有效值如 "GET","POST","CONNECT"等等;
        //設(shè)置提交的信息 JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));//全部數(shù)據(jù)使用HTTP協(xié)議中的 "POST" 操作來發(fā)送。

        return $this->close();
    }


    private function head()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "HEAD");

        return $this->close();
    }


    private function delete()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "DELETE");

        return $this->close();
    }


    private function put($params = [])
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));

        return $this->close();
    }


    private function get()
    {
        curl_setopt($this->ch, CURLOPT_HTTPGET, true);//TRUE 時會設(shè)置 HTTP 的 method 為 GET,由于默認(rèn)是 GET,所以只有 method 被修改時才需要這個選項。 

        return $this->close();
    }


    /**
     * 執(zhí)行并關(guān)閉
     * @return [type] [description]
     */
    private function close()
    {
        $data = curl_exec($this->ch);//執(zhí)行預(yù)定義的CURL
        $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);//獲取http返回值,最后一個收到的HTTP代碼
        curl_close($this->ch);//關(guān)閉cURL會話

        if (! $this->json) return $data;
        $res = json_decode($data, true);

        return $res;
    }


    /**
     * 是否是https
     * @return [type] [description]
     */
    private function https()
    {
        //SSL驗證
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https請求時要設(shè)置為false 不驗證證書和hosts  FALSE 禁止 cURL 驗證對等證書(peer's certificate), 自cURL 7.10開始默認(rèn)為 TRUE。從 cURL 7.10開始默認(rèn)綁定安裝。 
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE);//檢查服務(wù)器SSL證書中是否存在一個公用名(common name)。
        
        return $this;
    }


    /**
     * 請求時間
     * @param  integer $timeout [description]
     * @return [type]           [description]
     */
    private function out($timeout = 30)
    {
        //請求時間
        curl_setopt ($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout);//設(shè)置連接等待時間

        return $this;
    }

    private function error($message = 'error')
    {
        return $message;
    }

    public function __call($method, $params)
    {
        if (method_exists($this, $method))
        {
            return $this->$method(...$params);
        }
    }


    public static function __callStatic($method, $params)
    {
        $class = static::class;
        $Mcurl = new $class;
        
        if (method_exists($Mcurl, $method))
        {
            return $Mcurl->$method(...$params);
        }
    }
}

1 調(diào)用config url

<?php

namespace App\Model\Expert\Api;

class PCAP extends \App\Model\Base\Curl
{
    public $url = 'xx'; // 鏈接
    public $port = 'xx';  // 端口
    public $route = 'xx';  // 路由

    public static function getSizeAndCountOnPCAP($key, $direction)
    {
        $array = [
            "para" => [
                "type" => "querypacketinfo",
                "key" => $key,
                "direction" => $direction
            ]
        ];
        
        if (($temp = self::post($array)) && isset($temp['data']))
        {
            return explode('-', $temp['data']);
        }

        // count-size
        return [0, 0];
    }
}

2 自定義url

<?php

namespace App\Model\Expert\Api;

class PCAPShow extends \App\Model\Base\Curl
{
    public $url = ''; // 鏈接
    public $port = '';  // 端口
    public $route = '';  // 路由
    public $json = false;  // 關(guān)閉json轉(zhuǎn)換

    public static function getShowData($url)
    {
        $data = self::customUrl($url)->get();

        return $data;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、什么是CURL? cURL 是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、...
    茶藝瑤閱讀 4,832評論 0 6
  • cURL是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議和選項,如HTTP、FTP、TELNET等,能...
    司馬東陽閱讀 1,519評論 0 6
  • 原文地址:PHPcURL庫函數(shù)抓取頁面內(nèi)容(轉(zhuǎn))作者:巴克 cURL是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具...
    司馬東陽閱讀 1,267評論 0 3
  • 一、什么是CURL? cURL 是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、...
    伊Summer閱讀 1,400評論 0 4
  • curl 命令,是一個利用URL規(guī)則在命令行下工作的文件傳輸工具。 curl 支持文件的上傳和下載,所以是綜合傳輸...
    米撲閱讀 35,545評論 0 4

友情鏈接更多精彩內(nèi)容