Search code examples
phpfacebookfacebook-php-sdk

How do I make a post using Facebook's v3 SDK and PHP?


I am trying to make a post on the user's Facebook wall using my application. I also want to be able to access and display the person's user information afterward - but I'm getting stuck.

The code I have so far is below (with the sensitive parts masked, of course):

<?php
include("src/facebook.php");

$facebook = new Facebook(array(
    'appId'  => ##############,
    'secret' => #####################################,
));

$user = $facebook->getUser();

if ($user) {
  try {
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    // The access token we have is not valid
    $user = null;
  }
}
if (!$user) {
    $args['scope'] = 'offline_access, read_stream, friends_likes, email, read_stream, publish_stream, user_birthday,user_hometown, user_photos, uid, username, first_name';
    $loginUrl = $facebook->getLoginUrl($args);
}
 if (!$user): ?>
    <a href="<?php echo $loginUrl ?>">Login with Facebook</a>
<?php endif ?>

I can't figure out what's going wrong - and maybe I'm missing something critical? Any guidance would be appreciated.


Solution

  • 1) make sure to read the permissions documentation. For instance, offline_access has been deprecated and most of the permissions you are asking for does not exists!

    2) to post on the user wall you need the publish_stream permission (which you are already requesting)

    3) follow my tutorial, something like the below will get you started:

    $args = array(
        'message'   => 'Hello from my App!',
        'link'      => 'http://www.masteringapi.com/',
        'caption'   => 'Visit MasteringAPI.com For Facebook API Tutorials!'
    );
    $post_id = $facebook->api("/me/feed", "post", $args);
    

    4) improve your view (mixing PHP and HTML in your above code is not programmatically wrong but not recommended). And to answer your last request, the $user_profile would hold the information you need, just check the Facebook example to get started.

    5) try to improve your English and welcome to Stack Overflow!