Site icon Web Niraj

Facebook API: Uploading Photos to a User’s Profile

I get a lot of people asking me how to upload photos to a user’s profile on Facebook. One common misconception is that the Facebook JavaScript SDK does not support uploading photos, it only supports linking to photos.

Direct Approach:

In order to upload photos to Facebook, you must use the PHP (or similar) SDK. You first need to create a form that accepts multipart/form-data data:

echo '<form enctype="multipart/form-data" action="' . $graph_url . ' "method="POST">';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/><br/>';
echo 'Say something about this photo: ';
echo '<input name="message" type="text" value=""><br/><br/>';
echo '<input type="submit" value="Upload"/><br/>';
echo '</form>';

The $graph_url is the API endpoint you need to call to upload your photo. This is made up as follows:

  1. API URL: https://graph.facebook.com/me/photos
  2. Access Token: ?access_token=[user_access_token]

So, the $graph_url looks like:

https://graph.facebook.com/me/photos?access_token=[user_access_token]

Then, selecting a photo and clicking on “Upload” will upload the photo to the user’s profile and return the ID:

{
   "id": "1001234567890"
}

Note: The above code doesn’t reference the PHP SDK, but it will be needed to manage the login and retrieval of the user’s access_token.

Indirect Approach:

An alternative method for uploading photos to Facebook is to first upload the photo to your server (this could be for a number of reasons, e.g. you want to show the photo on your own website too). Then, you take the photo from your server and upload it to Facebook.

I’ve omitted the PHP code for handling uploads to your server since there are hundreds of examples already out there.

You can publish the uploaded photo by making a POST call to:

https://graph.facebook.com/me/photos?access_token=[user_access_token]

Passing in the url to the photo:

url=https://www.nirajandhina.com/wp-content/uploads/2012/06/582423_919310892046_1835741515_n-940x350.jpg

In this case, Facebook will return the Photo ID (id) and the Timeline ID (post_id):

{
   "id": "947213804386", 
   "post_id": "60506094_947213819356"
}
Exit mobile version