function curl (string $url, array $header = [], string $method = 'get', array $params = [], int $timeout = 0, bool $isJson = false, string $refer = '', array $userAgent = [], string $cookie = '') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// 设置请求头
if (!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
// 设置超时时间
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
// 设置cookie
if (!empty($cookie)) {
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
// 设置refer
if (!empty($refer)) {
curl_setopt($ch, CURLOPT_REFERER, $refer);
}
// 设置代理
if (!empty($userAgent)) {
curl_setopt($ch, CURLOPT_USERAGENT,$userAgent);
}
switch ($method) {
case 'get':
$url = strpos($url, '?') ? $url . http_build_query($params) : $url . '?' . http_build_query($params);
break;
case 'post':
if ($isJson) {
$params = json_encode($params);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
break;
case 'put':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
break;
case 'delete':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
php封装curl请求,包含几乎所有的常用参数
最新推荐文章于 2024-03-24 23:12:16 发布