PHP之curl實現http與https請求的(轉)

http get請求:

    function httpGet($url){  
        $curl = curl_init();  
        curl_setopt($curl, CURLOPT_URL, $url);  
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
        $res=json_decode(curl_exec($curl),true);  
        curl_close($curl);  
        return $res;  
    }  

http post請求:

    function httpPost($url,$post_data){   
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        // post數據  
        curl_setopt($ch, CURLOPT_POST, 1);  
        // post的變量  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
        $output=json_decode(curl_exec($ch),true);  
        curl_close($ch);  
        return $data;  
    }  

https get請求:

 

    function httpsGet($url){  
        $curl = curl_init();  
        curl_setopt($curl, CURLOPT_URL, $url);  
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);// https請求不驗證證書和hosts  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  
        $res=json_decode(curl_exec($curl),true);  
        curl_close($curl);  
        return $res;  
    }

 

http get請求:

    function httpsPost($url,$post_data){  
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        // post數據  
        curl_setopt($ch, CURLOPT_POST, 1);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https請求 不驗證證書和hosts  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  
        // post的變量  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
        $output=json_decode(curl_exec($ch),true);  
        curl_close($ch);  
        return $output;  
    }  

 

 

curl_init// 啓動一個CURL會話
curl_setopt$curlCURLOPT_URL$url// 要訪問的地址
curl_setopt$curlCURLOPT_SSL_VERIFYPEER0// 對認證證書來源的檢查
curl_setopt$curlCURLOPT_SSL_VERIFYHOST1// 從證書中檢查SSL加密算法是否存在
curl_setopt$curlCURLOPT_USERAGENT$_SERVER'HTTP_USER_AGENT'// 模擬用戶使用的瀏覽器
curl_setopt$curlCURLOPT_FOLLOWLOCATION1// 使用自動跳轉
curl_setopt$curlCURLOPT_AUTOREFERER1// 自動設置Referer
curl_setopt$curlCURLOPT_POST1// 發送一個常規的Post請求
curl_setopt$curlCURLOPT_POSTFIELDS$post// Post提交的數據包
curl_setopt$curlCURLOPT_TIMEOUT30// 設置超時限制防止死循環
curl_setopt$curlCURLOPT_HEADER0// 顯示返回的Header區域內容
curl_setopt$curlCURLOPT_RETURNTRANSFER1// 獲取的信息以文件流的形式返回
curl_exec$curl// 執行操做
if curl_errno$curlecho 'Errno'curl_error$curl//捕抓異常
curl_close$curl// 關閉CURL會話
return // 返回數據,json格式
相關文章
相關標籤/搜索