PHP请求第三方接口,需要使用curl发送请求,此方法做了简单的封装!
支持POST和GET的http和https请求,并且支持自定义header头和cookie!
/** * @param $url 接口地址 * @param $http_method 请求方式 * @param $data 请求数据 * @param $header 请求头(一维非关联数组) * @param $cookie 请cookie * @return 发送https的post请求 */ function http_curl($url, $http_method = 'GET', $data = '', $header = array(), $cookie = '') { $headers = array( 'Accept: application/json', ); $headers = array_merge($headers, $header); if ($cookie) { $headers[] = "Cookie: $cookie"; } $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //post提交方式 if ($http_method == 'POST' && $data) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } $res = curl_exec($ch); //返回结果 if ($res) { curl_close($ch); return $res; } else { $error = curl_errno($ch); curl_close($ch); return $error; } }