PHP 之CURL請求封裝GET、POST、PUT、DELETE

/**
 * @Description: curl請求
 * @Author: Yang
 * @param $url
 * @param null $data
 * @param string $method
 * @param array $header
 * @param bool $https
 * @param int $timeout
 * @return mixed
 */
function curl_request($url, $data=null, $method='get', $header = array("content-type: application/json"), $https=true, $timeout = 5){
    $method = strtoupper($method);
    $ch = curl_init();//初始化
    curl_setopt($ch, CURLOPT_URL, $url);//訪問的URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只獲取頁面內容,但不輸出
    if($https){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https請求 不驗證證書
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https請求 不驗證HOST
    }
    if ($method != "GET") {
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_POST, true);//請求方式爲post請求
        }
        if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //設置請求方式
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//請求數據
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模擬的header頭
    //curl_setopt($ch, CURLOPT_HEADER, false);//設置不須要頭信息
    $result = curl_exec($ch);//執行請求
    curl_close($ch);//關閉curl,釋放資源
    return $result;
}
相關文章
相關標籤/搜索