/**
* curl请求
* @param string $url
* @param array $fields
* @param bool $is_post
* @param bool $is_json
* @return mixed
*/
function request($url, $fields = array(), $is_post = false, $is_json = false)
{
$cl = curl_init();
if ($is_post) {
curl_setopt($cl, CURLOPT_POST, true);
if (!empty($fields)) {
if (is_array($fields) || is_object($fields)) {
$skip = false;
foreach ($fields as $key => $value) {
// POST文件时(instanceof \CurlFile),跳过http_build_query
if ($value instanceof \CurlFile) {
$skip = true;
}
}
if (!$skip) {
$fields = http_build_query($fields);
}
}
curl_setopt($cl, CURLOPT_POSTFIELDS, $fields);
}
} else {
if (!empty($fields)) {
$url = $url.(strpos($url, '?') === false ? '?' : '&').http_build_query($fields);
}
curl_setopt($cl, CURLOPT_HTTPGET, true);
}
curl_setopt($cl, CURLOPT_URL, $url);
if (stripos($url, 'https://') === 0) {
curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($cl, CURLOPT_SSLVERSION, 1);
}
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36');
curl_setopt($cl, CURLOPT_HTTPHEADER, array('Accept-Language: zh-CN,zh;q=0.9'));
curl_setopt($cl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($cl, CURLOPT_TIMEOUT, 60);
$response = curl_exec($cl);
$status = curl_getinfo($cl);
curl_close($cl);
if (isset($status['http_code']) && $status['http_code'] == 200) {
if ($is_json) {
$response = json_decode($response, true);
}
return $response;
} else {
return false;
}
}
版权属于:大卫科技Blog
本文链接:https://www.iyuu.cn/archives/396/
转载时须注明出处