为了使用curl 进行不同方式的请求,因此封装了此函数,支持get、post、put、delete方式的请求, 代码如下:
/**
* @param $url 请求的url
* @param array $params 请求的参数
* @param string $method, 请求的方法: get、post、 put、 delete
* @param bool $jsonType, 是否是json类型, 当值设置为 true 时,后端只能用 file_get_contents('php://input') 接收curl传递的参数
* @return array|mixed 返回一个结果数组
*/
function curl_request($url, $params = [], $method = 'get', $jsonType = false){
$ch = curl_init(); //请求的URL地址
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$method = strtoupper($method);
if($method == 'POST'){
if(!is_array($params)){
return ['state' => 'err', 'msg' => '请求参数必须是数组~'];
}
if($jsonType){ //需用 file_get_contents('php://input') 接收curl传递的参数
$jsonData = json_encode($params);
$header = array('Content-Type: application/json', 'Content-Length: ' . strlen($jsonData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
}else{ //需用 $_POST 方式接收curl传递的参数
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
}else if($method == 'PUT'){
if(!is_array($params)){
return ['state' => 'err', 'msg' => '请求参数必须是数组~'];
}
$jsonData = json_encode($params);
$header = array('Content-Type: application/json', 'Content-Length: ' . strlen($jsonData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置curl允许执行的最长秒数
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}