3

The problem the following code piece successfully sends POST request but doesn't send the data in $sendStream (the stream is valid and contains data - this has been verified):

curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-type: application/x-rethync-request'));
curl_setopt($request, CURLOPT_HEADER, true);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_INFILE, $sendStream);
curl_setopt($request, CURLOPT_INFILESIZE, stream_length($sendStream));
curl_setopt($request, CURLOPT_CUSTOMREQUEST, "POST");

$response = curl_exec($request);

I've read probably all cURL POST-related posts here on SO, but no luck. Why is the data not posted?

1 Answer 1

10

The missing piece was

    curl_setopt($request, CURLOPT_UPLOAD, 1);

The PHP documentation mentions this option briefly and nothing suggests that the option should be set. Still at least some (if not all) versions of cURL don't post data despite it's specified via CURLOPT_INFILE, unless CURLOPT_UPLOAD is also set.

NOTE: when you use this method to send the data, the response header will contain HTTP/1.1 100 Continue first, followed by HTTP/1.1 200 OK and so on. So when you parse response headers, beware of the first 100 Continue response (you'll need to strip it).

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you - that was the missing piece I was looking for as well.
It is worth mentioning that you can send string as stream. With PHP you could do it with few lines of code. $someString = 'String content'; $stream = fopen('php://memory','r+'); fwrite($stream, $someString ); $dataLength = ftell($stream); rewind($stream); Then adding those lines that were mentioned you can send binary data. CURLOPT_INFILE => $stream CURLOPT_INFILESIZE => $dataLength CURLOPT_UPLOAD => 1
@WojciechJakubas I am not sure that I understand the point of the comment. Yes, you can send the data from a memory stream, however the problem was different - the missing parameter caused cURL not to send anything. The origin of the data was probably not the source of the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.