php 使用curl时的请求头
Content-Type: application/x-www-form-urlencoded
正常的网页form 表单
提交时,浏览器发送的头部:Content-Type: application/x-www-form-urlencoded
, 发送的数据格式是k=v&k2=v2
Content-Type=multipart/form-data
multipart/form-data
我们知道这是用于上传文件的表单。包括了 boundary 分界符,会多出很多字节。
使用数组提供 post 数据时,CURL 组件大概是为了兼容 @filename 这种上传文件的写法,默认把 Content-Type 设为了 multipart/form-data。
虽然对于大多数服务器并没有影响,但是还是有少部分服务器不兼容。
所以需要post 表单提交时,需要指明头部
一条头部配置是一个value值,千万别写成 [‘Content-Type’ => ‘application/json’]
表单提交时:
$headers = ["Content-Type: application/x-www-form-urlencoded"];
$data = http_build_query($params, null, '&');
使用数组时:
$headers = ["Content-Type: multipart/form-data"];
$data = array();
使用json时:
$headers = ["Content-Type: application/json"];
$data = json_encode(array());
curl_post
function curl_post($url, $data, $headers = [], $timeout = 1, $mtimeout = 0)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
empty($headers) || curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
if ($mtimeout > 0) {
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $mtimeout);
} else {
if ($timeout > 0) {
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
}
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if (empty($result)) {
return [];
}
curl_close($ch);
$result = json_decode($result, true);
return $result;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接