Upload Photos to Facebook Using PHP SDK

0
SHARES

In my previous post, I set the stage to build more and more apps using facebook SDK. So we will be starting from that point with the assumption that authentication is already handled. Now we are going to upload a photo to facebook using facebook PHP SDK. The process is simple, but we need to take care certain points while coding our application.

Upload Photo to Facebook

First file we touch is config.php. If you go through the download files, we have added one more define variable for scope. scope variable request needed permissions from the facebook user. Now if our app has to upload a photo as facebook user, it needs publish_stream permission.

Now let us concentrate on our key file. We added one more folder for ‘upload-photos-to-facebook’. This folder contains an index.php file which demonstrate our photo uploading application. Next we need an html form with file uploader and a textbox. File uploader selects the image from local hard disk and text box accepts a message which is going to be the caption of the photo.

Here is the html markup for the form:

<form enctype="multipart/form-data" action=" " method="POST">
    Please choose a photo:
    <input name="source" type="file"><br/><br/>
    Say something about this photo:
    <input name="message"
           type="text" value=""><br/><br/>
    <input type="submit" value="Upload" class="btn btn-primary"/><br/>
</form>

You can observe that, I have left the action attribute blank. So when user submits Upload button, the page posts back the contents with values for each input fields. Our next task is to check if the input fields are set and if set upload it to facebook.

if(isset($_FILES["source"]["name"]))
{
    try {
        $facebook->setFileUploadSupport(true);
        $response = $facebook->api(
          '/me/photos/',
          'post',
          array(
            'message' => $_POST['message'],
            'source' => '@'.$_FILES["source"]["tmp_name"]
          )
        );
      }
      catch (FacebookApiException $e) {
        error_log('Could not post image to Facebook.');
      }
}

First we check if user has uploaded any file. Then it is mandatory to set setFileUploadSupport true for uploading files. Again we will be using graph api with ‘/me/photos’ connection. The request made is a post request and 2 values are passed as parameters. One is caption message and other is source path. If the request is successful, then the image will be uploaded to users wall.

Tags:

About Joby Joseph

Author of jobyj.in. I do a lot of research on web, APIs and social networks. Codes are mainly tried on PHP, jQuery, MySQL. Please support this blog by your facebook likes, twitter follow and RSS Subscribtion. Read more Google+