/**
* 模拟POST与GET请求
* @param string $url [请求地址]
* @param string $type [请求方式 post or get]
* @param bool|string|array $data [传递的参数]
* @param array $header [可选:请求头] eg: ['Content-Type:application/json']
* @param int $timeout [可选:超时时间]
*/
public function request($url, $type, $data = false, $header = [], $timeout = 0)
{
$cl = curl_init();
// 兼容HTTPS
if (stripos($url, 'https://') !== FALSE) {
curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($cl, CURLOPT_SSLVERSION, 1);
}
// 设置返回内容做变量存储
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
// 设置需要返回Header
curl_setopt($cl, CURLOPT_HEADER, true);
// 设置请求头
// 设置请求头
if (count($header) > 0) {
curl_setopt($cl, CURLOPT_HTTPHEADER, $header);
}
// 设置需要返回Body
curl_setopt($cl, CURLOPT_NOBODY, 0);
// 设置超时时间
if ($timeout > 0) {
curl_setopt($cl, CURLOPT_TIMEOUT, $timeout);
}
// POST/GET参数处理
$type = strtoupper($type);
if ($type == 'POST') {
if (is_array($data))
{
$data = http_build_query($data, null, '&');
}
curl_setopt($cl, CURLOPT_POSTFIELDS, $data);
}
if ($type == 'GET' && is_array($data)) {
if (stripos($url, "?") === FALSE) {
$url .= '?';
}
$url .= http_build_query($data);
}
curl_setopt($cl, CURLOPT_URL, $url);
//在http 请求头加入 gzip压缩
//curl_setopt($cl, CURLOPT_HTTPHEADER, array('Accept-Encoding:gzip'));
//curl返回的结果,采用gzip解压
//curl_setopt($cl, CURLOPT_ENCODING, "gzip");
// 读取获取内容
$response = curl_exec($cl);
// 读取状态
$status = curl_getinfo($cl);
// 读取错误号
$errno = curl_errno($cl);
// 读取错误详情
$error = curl_error($cl);
// 关闭Curl
curl_close($cl);
if ($errno == 0 && isset($status['http_code'])) {
$header = substr($response, 0, $status['header_size']);
$body = substr($response, $status['header_size']);
$array_data = json_decode(json_encode(simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $array_data;
} else {
return array('', '', $status, $errno, $error);
}
}
PHP curl请求post get 文件上传统一封装
最新推荐文章于 2022-11-09 14:19:00 发布