PHP中使用cURL實現Get和Post請求的方法


cURL是PHP的工具類,使用時參考官方文檔:http://php.net/manual/zh/book.curl.php

里面有詳細的使用說明以及參數介紹。

    /**
     * @param string $url
     * @return mixed
     */
    public function doGet($url)
    {
        //初始化
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,$url);
        // 執行后不直接打印出來
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳過證書檢查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不從證書中檢查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //執行並獲取HTML文檔內容
        $output = curl_exec($ch);

        //釋放curl句柄
        curl_close($ch);
        
        return $output;
    }

    /**
     * @param string $url
     * @param array $post_data
     * @param array | boolean $header
     * @return mixed
     */
    public function doPost($url,$post_data,$header)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        // 執行后不直接打印出來
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 設置請求方式為post
        curl_setopt($ch, CURLOPT_POST, true);
        // post的變量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        // 請求頭,可以傳數組
        curl_setopt($ch, CURLOPT_HEADER, $header);
        // 跳過證書檢查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不從證書中檢查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

其中跳過證書是為了訪問https。

 

技術交流群:576269252

--------------------------------------

聲明: 原創文章,未經允許,禁止轉載!

--------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM