0

I know of posting only binary:

$file_contents = file_get_contents("http://example.org/image.jpg");
curl_setopt($ch, CURLOPT_POSTFIELDS, $file_contents); 

as well as posting text along with binary from a file on disk:

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
  "name" => "peter",
  "msg" => "hello",
  "foo" => "@file/on/disk/image.jpg"
));

But what I can't figure out is how to post binary data directly from a variable (e.g. $file_contents) along with plain text key-value pairs. Is this possible with curl?

The reason I'm asking is that I'm using the facebook API to create events and need to upload an image along the rest of the event data. Because I'm getting the images from the internet it would be great if I didn't have to save them on disk before posting, then delete them from disk, but instead do the post directly with the data from file_get_contents() saved in a php variable.

4
  • What's wrong with just saving the file temporarily and deleting it after? Commented Aug 5, 2011 at 16:59
  • well, seems like an unnecessary step, you have to choose a unique file name, etc. Commented Aug 5, 2011 at 17:03
  • @mb21: tempnam() will do that for you. Commented Aug 5, 2011 at 17:34
  • thanks! okay, i guess i'll have to save them to disk then.. Commented Aug 6, 2011 at 9:44

1 Answer 1

1

You can pass parameters as querystring in the url, and pass the binary data in the postfields. On the receiving end all parameters can be retrieved from $_REQUEST

$file_contents = file_get_contents("http://example.org/image.jpg");

$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://example.com/test.aspx?name=peter&msg=hello');
curl_setopt($c, CURLOPT_POSTFIELDS, $file_contents);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_VERBOSE, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 0);
$cResponse = curl_exec($c);
curl_close($c);  
Sign up to request clarification or add additional context in comments.

Comments

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.