/** * @param string $url 请求地址 * @param array|string $params 请求参数 * @param string $method 请求方法 * @param array $header 请求头 * @param bool $multi post 数据是否进行url encode * @param bool $httpCode 是否返回http code * @return mixed * @throws Exception */ function curlHttp($url, $params, $method = 'GET', $header = [], $multi = false, $httpCode = false) { $opts = [ CURLOPT_TIMEOUT => 10, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => false, //不做证书校验,部署在linux环境下改为true CURLOPT_HTTPHEADER => $header ]; //根据请求类型设置特定参数 switch(strtoupper($method)) { case 'GET': if(!empty($params)){ $url .= '?' . http_build_query($params); } $opts[CURLOPT_URL] = $url; break; case 'POST': //判断是否传输文件 $params = $multi ? $params : http_build_query($params); $opts[CURLOPT_URL] = $url; $opts[CURLOPT_POST] = 1; $opts[CURLOPT_POSTFIELDS] = $params; break; default: throw new Exception('不支持的请求方式!'); } /* 初始化并执行curl请求 */ $ch = curl_init(); curl_setopt_array($ch, $opts); $data = curl_exec($ch); $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); //HTTPSTAT码 if($errorCode = curl_errno($ch)){ $data = json_encode(['code' => 1,'msg' => curl_error($ch)]); } curl_close($ch); if($httpCode){ $result = [ 'data' => $data, 'httpCode' => $httpStatus ]; return $result; } return $data; }