Wednesday, December 9, 2009

Uploading images to Flickr using PHP and CURL

I was just trying to upload images to Flickr using PHP and CURL. I struggled a bit, but got it in the end.

To upload of course one need to have API Key, Secret and Auth Token. To get an API Key please go through this link:
http://www.flickr.com/services/apps/create/apply/ .
There is a long process for getting auth token ...... which I am not discussing here.


So for uploading we have to pass api key, auth token, api signature and image. To form API Signature is the key thing here :)


$flickr_upload_url = "http://api.flickr.com/services/upload/";

$api_key = "Your api key goes here";

$auth_token = "Your auth token goes here";


Getting API Signature:
API Signature is md5 encryption of the fields which we pass to Flickr.
md5("your secret+api_key+your api key+auth_token+your auth token")


So here it should be:

$api_signature = md5("your secertapi_key$api_keyauth_token$auth_token");


Now create an array with all these fields
$data = array( 'api_key' => $api_key, 'auth_token' => $auth_token, 'api_sig' => $api_signature, 'photo' => "@".$_FILES['photo']['tmp_name']);
Here for image we should give complete path.

If you want to add any other fields in the array like Title for image, suppose here(title = image)
$data = array('title'=>'image', 'api_key' => $api_key, 'auth_token' => $auth_token, 'api_sig' => $api_signature, 'photo' => "@".$_FILES['photo']['tmp_name']);
then you should include this in API Signature. What ever the parameters you pass, all those parameters should be included in api signature's md5 encryption, other wise it will throw "Invalid Api Signature error".

So API Siganture will be:
$api_signature = md5("your secertapi_key$api_keyauth_token$auth_tokentitleimage");

The final code will be:
if(isset($_POST['submit'])){
$flickr_upload_url = "http://api.flickr.com/services/upload/";
$api_key = "
Your api key goes here";
$auth_token = "
Your auth token goes here";
$api_signature = md5("your secertapi_key$api_keyauth_token$auth_tokentitleimage");

$data = array('title'=>'image', 'api_key' => $api_key, 'auth_token' => $auth_token, 'api_sig' => $api_signature, 'photo' => "@".$_FILES['photo']['tmp_name']);

$ch = curl_init($flickr_upload_url);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

$postResult = curl_exec($ch);

}
Finally the response XML will be in $postResult variable, use your favourite method to read the XML. If the upload is successful then Photo Id will be returned. If not you will get the error message.

Bye............ :)

No comments:

Post a Comment