How to Upload and Read Facebook User Photos using PHP SDK

Last modified on August 14th, 2018 by Vincy.

Facebook provides options for uploading photos or videos via the interface. We can also post photos, videos, text data to Facebook by using their API. We can create our own application interface and use the Facebook API and post.

Facebook gives different channels to post photos or videos depending on the platform. Here, I have used the Facebook PHP SDK to upload photos to the Facebook edge.

How-to-Upload-and-Read-Facebook-User-Photos-using-PHP-SDK

For uploading photos to a Facebook page, the publish_pages and the manage_pages permissions are required with the page access token. The {user-id}/photos is specified for uploading user photos to the “photos” edge. While uploading photos, the image URL and the caption are set with the appropriate post params.

In this example, we have also stated the code for reading user photos using Facebook PHP SDK get function. In a previous Facebook developer example, we have seen how to read Facebook feed using PHP SDK. The {user-id}/photos will be mentioned in the get function with the access token.

The SDK functions call with the valid access token will read user photos from Facebook. The photo result is returned in a secured format which can be decoded to parse the data. The decoded data is used to display an image gallery with the Facebook photos. 

Creating User Interface to Upload Facebook User Photos 

This code is used to create the web interface for uploading the photo to the Facebook using PHP SDK. This interface contains a HTML form with input fields to get the image caption, file and a publish button. A photo icon is used to browse the file explorer to choose the photo to be uploaded to the Facebook. By submitting the Image file and caption, the photo will be uploaded to the specified target.

<div id="post-box">
    <form method="post" enctype="multipart/form-data">
        <textarea name="post_title" class="photo-caption"></textarea>
        <div id="post-box-footer">
            <input type="file" name="media-file-input"
                id="media-file-input" />
            <div class="photo-icon">
                <img src="photo.png" />
            </div>
            <input type="submit" name="save_to_fb" class="photo_publish">
        </div>
    </form>
</div>

In PHP the selected image and caption is received and posted by using the Facebook PHP SDK method. The image data is added to the array of param elements that are required to send the photo post request. The caption and the url parameters are used to set the image caption and the file address respectively. 

<?php
require_once 'FBUserPhoto.php';
$fbUserPhoto = new FBUserPhoto();
if(!empty($_POST["upload_to_fb"])) {
    $photoPath = "";
    if(!empty($_FILES["media_file_input"]["name"])) {
        $uploadFile = "uploads/" . basename($_FILES["media_file_input"]["name"]);
        if (move_uploaded_file($_FILES["media_file_input"]["tmp_name"], $uploadFile)) {
            $photoPath = $uploadFile;
        }
    }
    $fbUserPhoto->uploadPhoto($_POST["photo_caption"],$photoPath);
}
$postData = $fbUserPhoto->getPhotos();
?>

FBUserPhoto.php

This is the PHP class that loads the PHP SDK includes to send or receives user photo data to and from the Facebook edge. This class initializes the API credentials and instantiate Facebook API to access methods to read and upload the user photos.

The getPhotos() function uses the SDK get() method by specifying the {user-id}/photos edge with the access token. It returns the data related to the Facebook user photos. The returned data is decoded to get the photo thumbnail and the created time to form the image gallery.

The uploadPhoto() function of the FBUserPhoto class receives the image caption and the URL from the user and uploads it to the Facebook. This post action is similar to that of publishing text post to Facebook but the target and params will differ.

<?php
// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

require_once '../vendor/facebook/graph-sdk/src/Facebook/autoload.php';
require_once '../vendor/facebook/graph-sdk/src/Facebook/Exceptions/FacebookResponseException.php';
require_once '../vendor/facebook/graph-sdk/src/Facebook/Exceptions/FacebookSDKException.php';
require_once '../vendor/facebook/graph-sdk/src/Facebook/Helpers/FacebookRedirectLoginHelper.php';

class FBUserPhoto
{

    private $appId;

    private $appSecret;

    private $fb;

    private $accessToken;

    function __construct()
    {
        $this->appId = "API-KEY";
        $this->appSecret = "API-SECRET";
        $this->fb = new Facebook([
            'app_id' => $this->appId,
            'app_secret' => $this->appSecret,
            'default_graph_version' => 'v3.1'
        ]);

        $this->accessToken = "{access-token}";
    }

    function getPhotos()
    {
        $postData = "";
        try {
            $userPosts = $this->fb->get("/{user-id}/photos/uploaded?fields=picture,created_time,name", $this->accessToken);
            $postBody = $userPosts->getDecodedBody();
            $postData = $postBody["data"];
        } catch (FacebookResponseException $e) {
            // display error message
            exit();
        } catch (FacebookSDKException $e) {
            // display error message
            exit();
        }
        return $postData;
    }

    function uploadPhoto($caption, $photoPath)
    {
        $params = array(
            "caption" => $caption,
            "url" => "https://yourdomain.com/how-to-upload-facebook-user-photos-using-php-sdk/" . $photoPath
        );

        try {
            $postResponse = $this->fb->post("/{user-id}/photos", $params, $this->accessToken);
        } catch (FacebookResponseException $e) {
            // display error message
            print $e->getMessage();
            exit();
        } catch (FacebookSDKException $e) {
            print $e->getMessage();
            exit();
        }
    }
}

Note: 

  1. Integrate Facebook Login to get the credentials and access token. The access token should be created with the user_photos permission to read photos from the Facebook edge.
  2. The image URL specified with the url param should be a valid remote address. Otherwise, the SDK will throw the “invalid_request” “(#324) Missing or invalid image file” Exception.

Facebook Photo Upload Form Interface and User Photo Gallery Output

This is the output screenshot displays the web interface to upload the photo with caption to the Facebook by using PHP SDK. Also, it shows the gallery output created by tiling the Facebook user photos read from Facebook. The 100px wide photo thumbnail and the photo create time is added to each card of the gallery view.

Read-and-Upload-Facebook-User-Photo-Output

Download

This PHP code tutorial was published on August 14, 2018.

↑ Back to Top

Share this Article