最新消息:

cURL模拟HTTP请求(支持HTTPS) GET/POST/PUT/PATCH/DELETE

PHP yvsm 43浏览 0评论
function setHttpRequest($url,$headers,$params=array(),$method="GET") {
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method);

        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_HEADER, FALSE);
        
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查  
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在

        if($headers!=""){
            curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        }else {
            curl_setopt($ci, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        }
        switch (strtoupper($method)){
            case 'POST':
                    curl_setopt($ci, CURLOPT_POST, TRUE);
                
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                break;
            case 'PUT':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'PUT');
             
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
    
                break;
            case 'PATCH':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'PATCH');
             
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
            
                break;
            case 'DELETE':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
               
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
             
                break;
            default:
                curl_setopt($ci, CURLOPT_HTTPGET, TRUE);
                break;
        }
        $response = curl_exec($ci);
        $httpCode = curl_getinfo($ci);
        curl_close($ci);
        return $response;
    }

转载请注明:缘境的博客 » cURL模拟HTTP请求(支持HTTPS) GET/POST/PUT/PATCH/DELETE

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址