Last active
August 24, 2017 08:00
-
-
Save lifei6671/afd96fa7fa95c71e9f2faf828f82d457 to your computer and use it in GitHub Desktop.
PHP使用CURL发起请求
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 发起一个自定义请求 | |
* @param string $url | |
* @param string $method | |
* @param array $options | |
* @param array $headers | |
* @param array $vars | |
* @return HttpResponse|string | |
*/ | |
public static function send($url,$method = 'get' ,$headers = array(),$vars = array(),$options = array()) | |
{ | |
$request = curl_init(); | |
if (is_array($vars)) $vars = http_build_query($vars, '', '&'); | |
//http://www.php.net/manual/zh/function.curl-setopt.php | |
switch (strtoupper($method)) { | |
case 'HEAD': | |
curl_setopt($request, CURLOPT_NOBODY, true); | |
break; | |
case 'GET': | |
curl_setopt($request, CURLOPT_HTTPGET, true); | |
break; | |
case 'POST': | |
curl_setopt($request, CURLOPT_POST, true); | |
break; | |
default: | |
curl_setopt($request, CURLOPT_CUSTOMREQUEST, $method); | |
} | |
curl_setopt($request, CURLOPT_URL, $url); | |
if (!empty($vars)) { | |
curl_setopt($request, CURLOPT_POSTFIELDS, $vars); | |
} | |
# Set some default CURL options | |
curl_setopt($request, CURLOPT_HEADER, true); | |
curl_setopt($request, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setopt($request, CURLOPT_SSL_VERIFYHOST, false); | |
curl_setopt($request, CURLOPT_AUTOREFERER, true); | |
if(is_array($options) && empty($options) === false) { | |
# Set any custom CURL options | |
foreach ($options as $name => $value) { | |
curl_setopt($request, $name, $value); | |
} | |
} | |
if(is_array($headers) && empty($headers) === false) { | |
if (isset($headers['User-Agent'])) { | |
curl_setopt($request, CURLOPT_USERAGENT, $headers['User-Agent']); | |
} | |
if (isset($headers['Cookie'])) { | |
curl_setopt($request, CURLOPT_COOKIEFILE, $headers['Cookie']); | |
} | |
if (isset($headers['Referer'])) { | |
curl_setopt($request, CURLOPT_REFERER, $headers['Referer']); | |
} | |
if(isset($headers['Accept-Encoding'])){ | |
curl_setopt($request,CURLOPT_ENCODING,$headers['Accept-Encoding']); | |
} | |
$header = array(); | |
foreach ($headers as $key => $value) { | |
$header[] = $key . ': ' . $value; | |
} | |
curl_setopt($request, CURLOPT_HTTPHEADER, $header); | |
} | |
$response = curl_exec($request); | |
if($response){ | |
$response = new HttpResponse($response); | |
curl_close($request); | |
return $response; | |
}else { | |
$error = curl_errno($request).' - '.curl_error($request); | |
return $error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment