Change Facebook Page’s Cover Photo Using Graph API and Page API

Published on : December 5, 2012

Author:

Category: PHP


Facebook added new Page API to change cover photo of the fanpage.
To able to do this you need to ask manage_pages and user_photos permissions. manage_pages permission to get page access token and user_photos to upload photos to page. Facebook won’t allow users to upload image as cover photo – you have to upload a photo in an album and then give that photo id as cover photo. You could download the Facebook SDK for PHP here.

First we will ask our user to login with manage_pages and user_photos permission.


require 'facebook.php';

$facebook = new Facebook(array(
  'appId'  => FACEBOOK_APP_ID,
  'secret' => FACEBOOK_SECRET_KEY,
  'cookie' => false,
));

$user = $facebook->getUser();

$loginUrl = $facebook->getLoginUrl(array(
    'scope' => 'user_photos,manage_pages'
));

if ($user)
{
    try
    {
        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
        $permissions = $facebook->api('/me/permissions');
    }
    catch (FacebookApiException $e) {
        $user = null;
    }
}

if (!isset($permissions['data'][0]['user_photos']) or !isset($permissions['data'][0]['manage_pages']) )
{
  $user = null;
}

if (!$user)
{
echo "<script type="text/javascript">// <![CDATA[
top.location.href = '$loginUrl';
// ]]></script>";
  exit;
}

To work with page API, we need to get page access_token. We can get it by using /me/accounts graph api. We need to setFileUploadSupport true as we are uploading images. In this example I am just using an image located on the server. Then we are going to set a cover photo for a Page by issuing an HTTP POST to /PAGE_ID with a cover parameter.


$accounts = $facebook->api('/me/accounts');
for($i=0;$accounts['data'][$i];$i++)
{
    $pageAccessToken=$accounts['data'][$i]['access_token'];
    $pageId = $accounts['data'][$i]['id'];

    $facebook->setAccessToken($page_access_token);

    $args = array('image' =>'@'.realpath('/var/www/facebook.png'));
    try
    {
        $uploadedPhotoDetails = $facebook->api("/{$row['page_id']}/photos", 'post', $args);
    }catch(Exception $e){
        echo $e->getMessage();
    }

    if(isset($uploadedPhotoDetails['id']))
    {
        $args = array('cover' => $image_details['id'], 'offset_y' =>0);
         try {
             $cover_details = $facebook->api("/{$facebook_page['FacebookPage']['page_id']}", 'post', $args);
        }catch(Exception $e){
            $errors[] = $e->getMessage();
        }
    }
}


Leave a Reply

Your email address will not be published. Required fields are marked *