PHP CURL:手动设置content-length标头 [英] PHP CURL: Manually setting the content-length header

查看:7330
本文介绍了PHP CURL:手动设置content-length标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用PHP,CURL上传档案:

Say I upload a file with 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 );

现在假设我必须手动设置content-length标头。

Now assume I have to manually set the content-length 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);

如何测量身体的大小? (只是指定文件大小为内容长度似乎不工作)

How would I measure the size of the body? (just specifying the filesize as content length doesn't seem to work)

在另一个例子中,如果主体包含的数据不是一个实际的文件。 (通过postfields手动设置)在这种情况下,我将如何获得身体的内容长度?

In another example what if the body contains data that is not an actual file. (manually set by postfields) In that situation how would I get the content length of the body?

感谢任何轻微的流失,这似乎是一个艰难的问题。

Thanks for any light shed on this, it appears to be a tough issue.

推荐答案

要获得一个帖子正文的长度,请尝试格式化一个GET样式字符串的字段(aka param1 = value1& param2 = value2 )然后将该字符串设置为 CURL_POSTFIELDS with curl_setopt 。不必提供数组。您可以使用 strlen()来获取用于内容长度标头的值。

To get the length of a post body, try formatting the fields int a GET style string (aka param1=value1&param2=value2) then setting that string as the CURL_POSTFIELDS with curl_setopt. An array does not have to be supplied. You can simply use strlen() to get the value to use for the content-length header.

除了其他字段之外,还要发布一个文件(或多个文件),如上面的例子所示,您必须提供文件的值为 @ / path / to / file

If you are posting a file (or files) in addition to other fields, as you appear to be in the example above, you have to supply the value for the file as @/path/to/file, then get the filesize in bytes and add that to the total content-length.

因此对于上面的例子,假设文件 test.txt 在您的服务器的 / test dir 中,发布值字符串将是 file_name = @ / test / text.txt& submit = UPLOAD 。你必须 url_encode 这个字符串,在你分配它作为curl post值之前。要获取内容长度,您将获得该字符串的长度(后置网址编码),并将将其添加到 / test / test的filesize 。 txt

So for the above example, assuming the file test.txt is in the /test dir of your server, the post value string would be file_name=@/test/text.txt&submit=UPLOAD. You MUST url_encode this string as well, before you assign it as the curl post value. To get the content length you get the length of that string (post url-encoding) and add it to the filesize of /test/test.txt.

这篇关于PHP CURL:手动设置content-length标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆