假设我使用 PHP CURL 上传文件:
$postData = array();
$postData['file_name'] = "test.txt";
$postData['submit'] = "UPLOAD";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData );
现在假设我必须手动设置内容长度 header 。
$headers=array(
"POST /rest/objects HTTP/1.1",
'accept: */*',
"content-length: 0" //instead of 0, how could I get the length of the body from curl?
)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //set headers
$response = curl_exec($ch);
如何测量 body 的尺寸? (仅指定文件大小作为内容长度似乎不起作用)
在另一个例子中,如果正文包含不是实际文件的数据怎么办。 (由 postfields 手动设置)在那种情况下我如何获得正文的内容长度?
感谢您对此有所了解,这似乎是一个棘手的问题。
最佳答案
要获取帖子正文的长度,请尝试将字段格式化为 GET 样式字符串(又名 param1=value1¶m2=value2),然后将该字符串设置为 CURL_POSTFIELDS使用 curl_setopt。不必提供数组。您可以简单地使用 strlen() 来获取用于内容长度 header 的值。
如果除了其他字段之外,您还要发布一个(或多个)文件,如上例所示,您必须提供文件的值 @/path/to/file,然后获取文件大小(以字节为单位)并将其添加到总内容长度中。
因此对于上面的示例,假设文件 test.txt 位于服务器的 /test 目录 中,发布值字符串将是 file_name= @/test/text.txt&submit=上传。在将其分配为 curl post 值之前,您还必须 url_encode 此字符串。要获取内容长度,您需要获取该字符串的长度(经过 url 编码)并将其添加到 /test/test.txt.
关于PHP curl : Manually setting the content-length header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1916819/
phpCurl函数类,网上很多,这里分享一个万能phpcurl,包含phpcurl函数类模拟Curlgetpostheaderrefer携带Cookie模拟访问来源Refer模拟UseaAgentphp/***@author教书先生*@linkhttps://blog.oioweb.cn*@date2021年6月13日10:29:04*@msgPHPCurl封装的方法*/functionteacher_curl($url,$paras=[]){$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_SS
phpCurl函数类,网上很多,这里分享一个万能phpcurl,包含phpcurl函数类模拟Curlgetpostheaderrefer携带Cookie模拟访问来源Refer模拟UseaAgentphp/***@author教书先生*@linkhttps://blog.oioweb.cn*@date2021年6月13日10:29:04*@msgPHPCurl封装的方法*/functionteacher_curl($url,$paras=[]){$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_SS