function http_curl_v1($url, $postBody, $method = "POST")
{
// $all_url_arr = explode("?", $all_url);//请求的全部地址,此方法可以完全替代:file_get_contents
// $url = $all_url_arr[0];//请求地址
// $postBody = $this->url_to_arr($all_url_arr[1]);//转换成数组,方便提交
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded;text/json;charset=utf-8'
// 'Content-Type' => 'application/x-www-form-urlencoded'
// 'Content-Type' => 'multipart/form-data'
// 'Content-Type' => 'application/json'
);
// 初始化curl
$ch = curl_init();
// 设置curl参数
curl_setopt($ch, CURLOPT_URL, $url);
//设置头文件的信息作为数据流输出,GET好像要是1
curl_setopt($ch, CURLOPT_HEADER, 0);//改成1可以打印出结果,这样可以判断是否成功201就是成功
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);//15秒超时
curl_setopt($ch, CURLOPT_TIMEOUT, 30);//15秒超时
// curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postBody));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
} else if ($method == 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
} else if ($method == 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
}
//采集
$output = curl_exec($ch);
// var_dump($output);
// curl请求返回状态码
// $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);//这个信息太少,弃用
$curl_info = curl_getinfo($ch); //获取全部的,官方文档:https://www.php.net/manual/zh/function.curl-getinfo.php
$error = curl_error($ch);
// 关闭
curl_close($ch);
if ($error) {
// 请求发生错误,返回错误信息
$return_array = array(
'code' => $curl_info['http_code'],
'msg' => '网络异常',
'data' => $error,
'curl_info' => $curl_info);
return json_encode($return_array, JSON_UNESCAPED_UNICODE);//返回json
} else {
$output_array = json_decode($output, true);//解成数组
if (is_array($output_array)) {
unset($output_array['curl_info']);//去掉之前的
//增加CURL信息,方便排查错误 //demo 2022/1/19 13:40
$output_array['curl_info'] = $curl_info;
return json_encode($output_array, JSON_UNESCAPED_UNICODE);//返回json
} else {
return $output;//不是标准数组,直接返回错误。返回字符串
}
}
}
PHP通用型CURL
最新推荐文章于 2024-01-31 23:28:02 发布