cURL模拟HTTP请求(支持HTTPS)

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;
    }

posted @ 2017-08-31 21:15  selfim  阅读(3901)  评论(0编辑  收藏  举报