In this post , you will learn how you can send binary data through cURL in php. You might want to send binary data like image in some of the API calls viz Picasa API, Twitpic API etc.  If you send the image file as it is, it will passed to the API request as passed over the http, using content-type application/x-www-form-urlencoded. But API expected the binary data and hence your call fails everytime.

So to pass data in the binary format using the cURL request, we let the cURL pick the image itself. you just have to prefix ‘@’ letter before the filename, that is it. So a small protoype of this example would be :

 $file = $_FILES['my_image_file'];
 $post_field="@$file[tmp_name]"; //notice the @ sign prefixed. This does the trick
 * now write the cURL script which 
 * can post this $post_field to the URL 
 * you want to send data to

Here is the HTML file which has the file browse button.

<form method="post"  enctype="multipart/form-data" action="the_above_file.php">
   <input type="file" name="my_image_file" />

if you post data using ‘@‘ sign before the file name, the data is posted as binary, the newlines are preserved and conversions are never done.

Hope that saves your day !!
Sachin Khosla

Share this post: