views:

47

answers:

1

Hi, wondering if anyone can help me. I've been searching for a few days for help on how to publish photos to Facebook using the API. I came across the following script that seems to work for everyone however I am unsure how to connect this to a form where users can select the photo from their hard drive and upload it. Can anyone point me in the right direction?

PHP Code:

$token = $session['access_token'];
$file= 'photo.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '@' . realpath($file);

$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);

Code for the form:

<form action="<?=$PHP_SELF;?>" enctype="multipart/form-data" method="POST"> 
 <input name="MAX_FILE_SIZE" type="hidden" value="10000000" /> 
 <input id="file" name="file" type="file" /> 
 <input name="submit" type="submit" value="Upload" />
</form>
A: 

Clark,

The php script receives the file and its details in the $_FILES variable.

For Eg. If you are uploading a file names Image1.jpg then the $_FILES array would have the following values

array(1) { ["file"]=> array(5) { ["name"]=> string(21) "Image1.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(23) "C:\wamp\tmp\phpD1DF.tmp ["error"]=> int(0) ["size"]=> int(355315) } }

Here, name = actual file name type = file type tmp_name = path of the temp location where the file is uploaded on the server size = file size

For uploading the file to facebook the values that you should be interested in the "name" and the "tmp_name".

So the arguments that you should send to facebook for the photo upload should look something like this

$args = array( 'message' => 'Photo from application', );

$args[$_FILES['file']['name']] = '@' . $_FILES['file']['tmp_name'];

I think this should work for you.

Btw, i checked out the facebook doc for photo upload @ http://developers.facebook.com/docs/reference/api/photo they say the file name should be passed in the param "source", so if the above arguments dont work for you, you can try

$args = array( 'message' => 'Photo from application', 'source' => '@' . $_FILES['file']['tmp_name'] );

Give it a try :) Hope this helps.

Kartik
That worked great, thanks very much!
Clark Caughey