PHP CURL: manually setting content length header

Let's 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 ); 

Now suppose I need 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 to measure body size? (just specifying the file size as the length of the content does not work)

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

Thanks for any light on this, this seems to be a difficult problem.

+7
php curl
source share
2 answers

To get the message body length, try formatting the int fields in the GET style line (aka param1=value1¶m2=value2 ), and then set this line as CURL_POSTFIELDS using curl_setopt . An array is not required. You can simply use strlen() to get the value for the content length header.

If you send a file (or files) in addition to other fields, as you seem in the example above, you should specify the value for the file as @/path/to/file , then get the file size in bytes and add this to the total length of content.

So, for the example above, assuming the test.txt file is located in your server’s /test dir , the line for the post value will be file_name=@/test/text.txt&submit=UPLOAD . You MUST also url_encode this line before assigning it as a curl post value. To get the length of the content , you get the length of this line (post url-encoding) and add it to the size of the /test/test.txt file .

+7
source share

This sounds wrong. The generated data will include subheadings, and Content-Length should also include these subheadings. And since there is a border in the headers, it can include this and this data, this whole thing cannot work (the size cannot be set, not knowing exactly what the full request will be).

Actually, the only one that can calculate the size, from what I see, is cURL itself. But this is not so. 8-p

+1
source share

All Articles