Using PHP and cURL to POST a file

I’ve been experimenting with Share on Ovi this week (seems only proper now that we’re all part of the same family now). Turns out to be a very nicely put-together web app in the Flickr genre, but with much better mobile integration, at least on Nokia devices.

Programatically uploading media to Share on Ovi can be done using the Atom Publishing Protocol: the basic idea is that you do an HTTP POST of binary image data, get back a response that contains an endpoint for doing an HTTP PUT with the image meta-data.

While I’m an old hand at using PHP and cURL together, this was the first time I’d needed to do an HTTP POST that wasn’t a standard key-value pairs, but rather simply a binary file. Turns out this is pretty easy, once you figure it out; the keys are:

$upload = file_get_contents($filename);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);
curl_setopt($ch, CURLOPT_POSTFIELDS, $upload);

Once I got this together, and figured out the secret WSSE voodoo required to authenticate, everything fell into place: here’s the first image I uploaded with my cool new PHP class.


Peter Rukavina's picture
Peter Rukavina on July 10, 2008 - 16:34 Permalink

Follow-up: I’ve been experimenting with a script to migrate photos from Flickr to Share on Ovi and it appears to be working (see my Share on Ovi page for some early results). I’ve got the title, description and tags migrating, along with the original image and all its EXIF data.

Peter Rukavina's picture
Peter Rukavina on July 11, 2008 - 21:35 Permalink

I’ve just released the source for a class that allows PHP5 to programatically upload images to Share on Ovi using the Atom Publishing Protocol.

oasisfleeting's picture
oasisfleeting on January 29, 2011 - 05:35 Permalink

Finally, the extra little help I needed.
In this example he is not url-ifying the post data and posting a query string along with the field array. I WAS url-ifying the post data for a query string and it was causing problems.

So do like he did and just pass the $fields array into the setopt

$contents = file_get_contents($_FILES[‘file’][‘tmp_name’]);

$fields = array(
‘fileid’=>/*date(‘YmdGisu’) .*/ $_FILES[“file”][“name”],

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_USERAGENT, “Mozilla/4.0 (compatible;)”);

//execute post
$output = curl_exec($ch);