用PHP封装一个强大且通用的CURL方法
支持:get、post、put、delete、patch、options
直接上代码:
/**
* @function 强大且通用的cURL请求库
* @param $url string 路径
* @param $method string 请求方式 如:get、post、put、delete、patch、options
* @param $payload array|string 荷载 如:['foo' => 'bar', 'upload_file' => new CURLFile(file_path)]或json{"foo":"bar"}
* @param $request_header array 请求头 如:['Content-Type' => 'json', 'Set-Cookie' => 'foo']
* @param $time_out int 超时秒数 如:10,(单位:秒)
* @return array [bool 请求是否成功, string 错误内容, [int http状态码, array 响应头, string 响应主体内容]];
*/
function curl($url, $method = 'GET', $payload = [], $request_header = [], $time_out = 10) {
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL, $url);
$method = strtoupper($method);
if ($method == 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
} else if ($method == 'PUT') {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS