PHP中使用CURL實現GET、POST、PUT、DELETE請求


/**
 * @param $url
 * @param $data
 * @param string $method
 * @param string $type
 * @param array $headers
 * @return bool|string
 */

function curlpost($url,$data,$method = 'GET',$type='json',$headers=[])
{
    try{
        //初始化
        $ch = curl_init();
        $headers[] =  "cache-control: no-cache";
        $contentType = [
            'form-data' => 'Content-Type: multipart/form-data',
            'json'      => 'Content-Type: application/json',
        ];
        if($method == 'GET'){
            if($data){
                $querystring = http_build_query($data);
                $url = $url.'?'.$querystring;
            }
        }
        $headers[] = $contentType[$type];

        // 請求頭,可以傳數組
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);         // 執行后不直接打印出來
        if($method == 'POST'){
            if($type=='json'){
                $data = json_encode($data);
            }
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');     // 請求方式
            curl_setopt($ch, CURLOPT_POST, true);               // post提交
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);                 // post的變量
        }
        if($method == 'PUT'){
            curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        }
        if($method == 'DELETE'){
            curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);  // 最大執行時間
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);  // 最大執行時間
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書檢查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不從證書中檢查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        $output = curl_exec($ch); //執行並獲取HTML文檔內容
        $err = curl_error($ch);
        if($err){
            //\Illuminate\Support\Facades\Log::info('curl錯誤');
            //\Illuminate\Support\Facades\Log::error($err);
        }
        curl_close($ch); //釋放curl句柄
        return $output;
    }catch (\Exception $e){
        \Illuminate\Support\Facades\Log::info('curl異常');
        \Illuminate\Support\Facades\Log::error($e);
        return false;
    }
}

 


免責聲明!

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



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