Web Niraj
  • Facebook
  • Flickr
  • Github
  • Linkedin
  • Twitter
  • YouTube
Online portfolio, code examples and developer blog
  • About
  • Contact
  • Portfolio
  • WordPress
Search the site...
  • Home
  • Blog
  • Facebook API: Posting a Status Update Using PHP SDK 4.0.x

Facebook API: Posting a Status Update Using PHP SDK 4.0.x

64

The Facebook Documentation for PHP SDK 4.0 is basic at the moment, and doesn’t fully document common uses of the API. Therefore, I’m rewriting old tutorials to work with the new PHP SDK 4.0 and Graph API 2.0. This tutorial covers how to post a status update to the user’s timeline in the background using the API.

First off, you need to add the publish_actions permission to your app to allow automatic posting of text, links, or photos to the timeline. This permission will need to be approved by Facebook before your users will be able to approve it. Once approved, your users will see a dialog similar to the one below:

Publish Actions Permission Dialog

In order to post a status update to the timeline, we must make a POST call to the /{user_id}/feed API endpoint. This endpoint remains unchanged from Graph API v1.0. The user must be logged in and have a valid access_token for the API call to work.

For the logged in user, the endpoint we need is below. At the minimum, we need to include the message parameter and access_token. At the minimum, the message parameter should be passed.

If successful, Facebook will return an ID for the post, which is made up of your User ID and the ID for the post.

Array ( [id] => 60506094_10100387108404056 )

If you want to post images, links etc, you can include additional parameters in your API call. The following are just a few parameters you can use:

  • message – the text for the status update, e.g. “TGI Friday!”.
  • link – A URL to a website you want to link to
  • picture – URL of an image you want to include in the update
  • name – The name of the link attachment
  • caption – The caption of the link (appears beneath the link name)
  • description – The description of the link (appears beneath the link caption)

For example, if I wanted to post a link to this article, my data would look like:

The status update itself will look something like:

FB Status Update v4.0.x

A full list of properties to use with the /feed API call can be found on Facebook’s Documentation for Feeds.

Facebook, Facebook Graph API, Facebook PHP SDK 4.0, PHP

64 comments on “Facebook API: Posting a Status Update Using PHP SDK 4.0.x”

  1. Lhakpa Dorji says:
    June 13, 2014 at 9:34 AM

    Hi there,
    can we retrieve all the post from the particular group using facebook API v4.0.0 using php.

    Reply
    • Niraj Shah says:
      June 13, 2014 at 2:05 PM

      Yes, you can call the following endpoint: {group_id}/feed. If the group is private, you won’t be able to retrieve the posts.

      E.g.:

      $groupFeed = (new FacebookRequest( $session, 'GET', '/{group_id}/feed' ))->execute()->getGraphObject()->asArray();
      echo print_r( $groupFeed, 1 );
      Reply
      • lhakpadorji says:
        June 17, 2014 at 4:11 AM

        Thank you 🙂

  2. CorentinGC says:
    June 20, 2014 at 10:34 PM

    Hi, thank you for your tutorials, really helped me !
    But now, i block with page publishing, can you make a tutorial on it ? How can I use the access token of my pages to publish ?

    Thanks

    Reply
    • CorentinGC says:
      June 20, 2014 at 10:36 PM

      Nevermind… I read the tutorial again, and it’s ok, thank you again 🙂

      Reply
  3. b0b0123 says:
    July 17, 2014 at 4:42 PM

    Hello, been trying to understand this but I am really confused and I don’t know how to integrate it into my code. Would I be able to get the user to browse for a photo from their computer to upload to facebook? I followed the answer from this question: http://stackoverflow.com/questions/24317721/post-picture-facebook-graph-api-php but stuck step 2 and 3. It is also different in syntax to yours. I am confused. Would his solution work? I asked him for help but he wasn’t being helpful. I am so sorry to bother you. Thanks

    Reply
    • Niraj Shah says:
      July 18, 2014 at 10:00 AM

      The answer on StackOverflow is overly complicated. If you use my code together with the upload form on StackOverflow, you can achive the same result. Add in the picture parameter to the /me/feed API call and you can upload a image directly to your timeline. You will obviously need to upload the photo to your server first, before it can be saved to Facebook.

      Reply
      • b0b0123 says:
        July 18, 2014 at 10:31 AM

        Hello, thank you for taking the time to look at the code… what do you mean upload the photo to the server first? Would I be able to do that via the form? So that the user (me) can browse and submit a picture from my computer and upload it to the server via my app and then onto facebook? (Sorry, probably really obvious what to do but I really slow….) Thanks again, for being really patient with me

      • Niraj Shah says:
        July 18, 2014 at 12:23 PM

        You need to use HTML and a PHP script to upload the photo to your server before sending it to Facebook. Use Google to find some sample code on how to achieve this. The user will be able to browse for a photo, and your code will need to upload the photo, save it to the server and then send it to Facebook using the Graph API.

  4. b0b0123 says:
    July 18, 2014 at 12:15 PM

    Also, using your code in a new file: upload.php, do I need to include all the facebook files again? Or do I simply just put because it’s showing errors, saying session is undefined

    Reply
    • Niraj Shah says:
      July 18, 2014 at 12:24 PM

      Yes, all the Facebook SDK files need to be included everywhere you intend to use Facebook. Otherwise, any attempt to call functions from the SDK will result in an error. To simplify things, you should using PHP Includes to easily include common code into each file (hint: Google how to do this too).

      Reply
      • b0b0123 says:
        July 18, 2014 at 12:30 PM

        Okay! Thank you for the advice and hints! One more question, in the upload.php (or any other files I create) do I need to do the whole create session thing again and app id thing again? Thanks!

      • Niraj Shah says:
        July 20, 2014 at 11:13 AM

        Yes, you need to repeat pretty much everything again. Ideally, you just need to make sure the user session is valid on this page.

  5. b0b0123 says:
    July 18, 2014 at 2:41 PM

    Yay! I managed to upload a photo to the server! I think I’m getting a better idea how my app works now, thanks to you! But got a problem with the include.php thing, it doesn’t recognise it? I get the error that FacebookSession is not defined.. I copied and pasted all the require_once and use into a file called include.php and then in my index.php I called it include (‘include.php’); <– I've tried so many different syntaxes too! Where am I going wrong? Thanks! (sorry for spamming.)

    Reply
    • Niraj Shah says:
      July 20, 2014 at 11:12 AM

      Post your issue on StackOverflow and see if someone can help you out.

      Reply
      • b0b0123 says:
        July 21, 2014 at 10:00 AM

        Okay, thanks for your help 🙂

  6. Lisa Johnson says:
    July 21, 2014 at 10:48 PM

    Hi Niraj, I am trying to get the publish_actions permission for my app, but could not figure out where to obtain these extended right. I don’t want to make my app public right now and just want to play with it, so I do not want to submit anything for review. Is it possible that I give just extended permissions to the administrator of the app, or do I always need to submit my app for review in order to get the publish_actions permission.

    Thanks a lot!
    Lisa

    Reply
    • Lisa Johnson says:
      July 21, 2014 at 11:44 PM

      Hi Niraj, I amnage to solve the problem and I can see now the post in a Facebook group where I am the admin. However, if I ask a friend if my post appears in the group, he tells me that it is not shown. I guess, it has something to do that my app is still running in the sandbox and I have to submit my app for review to facebook. Is this correct?

      Do you know if facebook terms of use allow an app to post content to my own group?

      Reply
      • Niraj Shah says:
        July 22, 2014 at 10:41 AM

        Hi Lisa,

        I’ve tested Group Status Updates and found that Status Updates from Sandboxed Apps do not appear in the group until it’s made public. You can easily make the app public without having to get the permissions reviewed by Facebook. You just need a contact email address in the settings and you can make the app available to the general public. There are no restrictions for apps for posting to groups.

  7. b0b0123 says:
    July 22, 2014 at 12:42 PM

    Hello. I was able to post a status but then I sometimes get this error: Catchable fatal error: Argument 1 passed to Facebook\FacebookRequest::__construct() must be an instance of Facebook\FacebookSession, null given.. I tried to do it for ‘source’=>{‘image-data’} and I get the same error..

    Reply
    • Niraj Shah says:
      July 22, 2014 at 3:25 PM

      Your code should be something like $request = new FacebookRequest( $session, 'GET', '/me' );. The first parameter to FacebookRequest needs to be $session, from a valid Facebook Session.

      Reply
      • b0b0123 says:
        July 23, 2014 at 11:24 AM

        I have that for my first request. But I am making a second api request to post a photo. Somehow there is no longer a session when I call this request so I’ve created one again like this:

        $session = new FacebookSession( $_SESSION[‘fb_token’]);
        $request = new FacebookRequest(
        $session,
        ‘POST’,
        ‘/me/photos’,
        array (
        ‘source’ => file_get_contents($location.$name),
        )
        );

        But I get errors.. Please can you have a look at my code on stackoverflow?

        http://stackoverflow.com/questions/24885784/facebook-api-sdk-4-0-post-a-photo-onto-facebook

        Thank you.

      • Niraj Shah says:
        July 23, 2014 at 4:27 PM

        I’ve replied to your Stackoverflow Question. I found two issues that were causing issues – fix both and your code will work. Your session is being destroyed because you have session_destroy() in your code – that needs to be removed. As for the source, do this instead: 'source' => '@' . $location . $name.

      • Moxet Khan says:
        January 14, 2015 at 6:44 AM

        Perfect! it solve my problems, i was using $sess
        Thank you

  8. Lisa Johnson says:
    July 23, 2014 at 3:09 PM

    Great! Thanks a lot Niraj 🙂

    Reply
  9. Lisa Johnson says:
    July 24, 2014 at 9:29 PM

    Hi Niraj,

    Again me 🙂 I tried now to read from the feed of a facebook group. As you described above this only works if the group is open. I wonder however, if there is no way to read the content of a private group, when I am a member of that group or even its admin. It looks a bit strange to me that I can post to closed groups when I am a member of this group, but cannot read their content. Any idea how this could work?

    Thanks a lo!

    Reply
  10. Lisa Johnson says:
    July 24, 2014 at 10:37 PM

    Hi Niraj,

    I managed to figure out myself :). Do you know if it is possible to reply (publicly) in the group to posts of other people? Is this possible or does my app need special rights for this?

    Cheers, Lisa

    Reply
    • Niraj Shah says:
      July 25, 2014 at 10:17 AM

      Hi Lisa,

      It should be possible to reply to posts within a group (close, public, secret), but it would be publicly. Only members of the group will be able to see the reply, unless it’s an open group. I haven’t tried this myself so cannot confirm. You will only need to user_groups and publish_actions permissions.

      Reply
      • Lisa Johnson says:
        July 25, 2014 at 10:46 AM

        Hi Niraj,

        but for the publish_actions permission I need to submit my app for review, no?

      • Niraj Shah says:
        July 25, 2014 at 4:21 PM

        Yes, once you have developed your app, the permission will need to be reviewed before users can use it.

  11. David Brown says:
    July 25, 2014 at 4:26 AM

    Hey, I’m currently just testing and configuring my application and my end goal is to be able to post on a users wall.

    I understand that we need to get approval for publish_actions. How hard is it to actually get approval, and can I get approval without having a full application/website? I would really just like to use permissions to test some features I am working on a for a potential application.

    Thanks!

    Reply
    • Niraj Shah says:
      July 25, 2014 at 10:21 AM

      You can build a website or app without getting approval for any permissions you require, the only drawback is that those permissions will only be available to application administrators, developers and testers. It does mean that you can test any feature you want requiring any permissions you want. You should only submit your application for review once it’s fully functionality. Facebook has said reviewing can take up to 2 weeks.

      Reply
  12. Lisa Johnson says:
    July 26, 2014 at 3:16 PM

    Hi Niraj,

    I tried the following code to reply to one of my own posts in a test group I created:

    try {	  
      $request = new FacebookRequest(
      $session,
      'POST',
      '/{my group id}/feed/posts/{my post id}',
      array (
        'message' => 'This is a test',
      )
    );
    $response = $request->execute();
    $graphObject = $response->getGraphObject();
    
      } catch( FacebookRequestException $ex ) {
        // When Facebook returns an error
        // handle this better in production code
        print_r( $ex );
      } catch( Exception $ex ) {
        // When validation fails or other local issues
        // handle this better in production code
        print_r( $ex );
      }
    


    When I execute the code, then I get the exception saying that “Unknown path components:..”.

    Any idea how I can fix this?

    Many thanks!
    Lisa

    Reply
    • Niraj Shah says:
      July 26, 2014 at 3:35 PM

      You are using the incorrect path to the Group Post. Try this instead:

        $request = new FacebookRequest(
        $session,
        'POST',
        '/{my post id}/comments',
        array (
          'message' => 'This is a test',
        )
      );
      $response = $request->execute();
      $graphObject = $response->getGraphObject();
      

      Reply
  13. b0b0123 says:
    July 30, 2014 at 5:33 PM

    Is it possible to change the privacy settings of the post when making the api request? I know at the start, the user accepts to share with friends… but can it be changed for individual posts?

    Reply
    • Niraj Shah says:
      July 30, 2014 at 10:24 PM

      Yes, you can override the privacy setting for individual posts using an additional parameter (see documentation). However, the user still determines the max privacy level. I.e. if a friend sets max privacy to Friends, your app cannot make the post public or viewable to Friends of Friends.

      Reply
      • b0b0123 says:
        July 31, 2014 at 10:38 AM

        Do you mean the FQL? Am I going to have to do a database to do that? I did the additional parameter like this: ‘privacy’ => ‘{value: “EVERYONE”}’ but I don’t think that’s the one you’re talking about… because it doesn’t override the initial privacy setting. I want the user to be able to determine the privacy level of each post.

      • Niraj Shah says:
        July 31, 2014 at 10:44 AM

        No, do not use FQL – it will be deprecated soon, and it has nothing to do with having a database. You need to use the privacy parameter as you’ve mentioned. As I said, it won’t override the maximum value the user has set when they first authorise your application. Your users would need to set max privacy level to public if they want to be able to use all the privacy levels, otherwise you will be limited to what they set.

        If I set the max level to SELF (i.e. only me), no matter what I set in the privacy level in the post, it will be limited to only me (as that is the max privacy level I’ve allowed the app to use).

  14. b0b0123 says:
    July 31, 2014 at 11:18 AM

    Oh right. So that initial privacy thing is the max privacy. So there is no way round it, THEY have to select public at the start? hmmm okay. You’re really helpful! Thank you!!!

    Reply
  15. Ståle Lindblad says:
    August 10, 2014 at 11:07 PM

    Hi,
    thanks for at great blog.
    How do I check which permissions are granted with the new PHP SDK? I need to check if ‘manage_pages’ is granted for my WEB-app.

    Reply
    • Niraj Shah says:
      August 11, 2014 at 3:24 PM

      You can make the following API call to see which permissions have been granted by the user:

      $graphObject = (new FacebookRequest( $session, 'GET', '/me/permissions' ))->execute()->getGraphObject()->asArray();

      Reply
  16. Lisa Johnson says:
    August 18, 2014 at 3:15 PM

    Dear Niraj,

    When I post to a group it always shows “posted via TestApp”. Can I somehow prevent this and make the post look like as ti was done as a normal user?

    Regards,
    Lisa

    Reply
    • Niraj Shah says:
      August 18, 2014 at 9:25 PM

      Hi Lisa,

      No, there is no way to disable this. It’s something Facebook puts in so users know the origin of the post. I’ve seen developers try to circumvent this by changing the name of their app to ..

      Reply
  17. Agus Tamanuri says:
    September 23, 2014 at 2:06 PM

    Hi mr Niraj ..

    How to request permission for publish_action explanation text and instructions text in facebook application ?

    I am newbie n please help me to my problem

    Thanks before

    Reply
    • Niraj Shah says:
      September 24, 2014 at 1:13 PM

      Please see this tutorial on how to add permissions to the login link. To get the permission approved, you need to include clear step-by-step instructions on how the permission is used.

      Reply
  18. Xoni says:
    March 2, 2015 at 5:45 AM

    Hi there, is it possible to create a new post that will be hidden in the users timeline. It will only be shown to the friends of the user but not on their timeline. Thanks.

    Reply
    • Niraj Shah says:
      March 3, 2015 at 9:59 AM

      No, you cannot hide content on the user’s timeline and have it visible to friends. You can do it the other way around, with content hidden to friends.

      Reply
      • Xoni says:
        March 3, 2015 at 2:00 PM

        Yesterday I found that there exists an option called “no_feed_story” property when posting using the Graph Api, but I haven’t tested it yet, maybe it works….

      • Niraj Shah says:
        March 3, 2015 at 7:26 PM

        The no_feed_story parameter is actually used to suppress Facebook from creating newsfeed posts when uploading photos, setting cover images or publishing OpenGraph actions. It means the post isn’t published to the user’s feed, which also effectively means friends don’t see it either. It’s covered in my “Updating the Page Cover Image Programmatically” tutorial.

      • Xoni says:
        March 3, 2015 at 7:37 PM

        I also saw a script that someone was selling, and he wrote that the script does the following:
        – when the user visits the website, after authorising the Facebook Application it automatically creates a new posts that will not be shown on the user timeline, but it will still appear on ticker and users friend.
        Do you think this is possible? Or he was lying.

        thanks.

      • Niraj Shah says:
        March 3, 2015 at 7:50 PM

        As my understand of the Facebook platform goes, it’s not possible to show something to friends unless it’s also visible on the user’s timeline. Also, this application you speak off is against Facebook ToS as apps aren’t allowed to post to the user’s timeline without explicit permission. Accepting the publish_actions permission isn’t consent.

  19. abdulbaquee says:
    March 7, 2015 at 8:32 PM

    Hi Niraj,

    How do I set cronjob for posting on my Facebook admin page using graph api php sdk 4.0 ?

    Reply
    • Niraj Shah says:
      March 10, 2015 at 12:08 PM

      Write the script to publish to page as you normally would, but hard-code in the page access_token. You can then call the script via command-line to test, and then turn it into a cron (which will call the command-line on a scheduled basis). You’ll have to ask your hosting provider for instructions on setting up cronjobs (I set them up using crontab -e on command line, but you may have access to a interface)

      Reply
      • abdulbaquee says:
        March 10, 2015 at 12:21 PM

        Hi Niraj,

        Thank you for your quick reply. 🙂

  20. Fred says:
    April 13, 2015 at 3:59 PM

    Hi Niraj,

    Nice article !
    I’m wondering what are the conditions to meet for Facebook to accept the review of “taggable_friends” and “publish_actions” permission.
    I’m exactly in the case your sample where you suggest a friend to take a look to your new tutorial on your blog.
    Do you think the review of this 2 permissions can be accepted by Facebook for such a usage (suggesting a friend to come to your site) ?

    Thanks a lot…

    Fred

    Reply
    • Niraj Shah says:
      April 17, 2015 at 9:02 AM

      As long as you follow the guidelines, the permissions will get approved. For publish_actions actions, that means sharing to the timeline only if the user has explicitly allowed you to do so. Make sure you provide detailed instructions on how each permission is used and where to find it in your application.

      Reply
  21. febriani says:
    June 7, 2015 at 11:36 PM

    hi, can you help me, how can i display my facebook wall post from people and show the comment link like facebook?

    Reply
    • Niraj Shah says:
      June 22, 2015 at 9:25 AM

      This is not easily doable. You would need to recreate all the facebook functionality found on the website, and you’d be revealing your private Facebook stream to users. Not really worth the effort.

      Reply
  22. tienluc says:
    June 16, 2015 at 9:01 PM

    Hello, can I retrieve all my group ids using facebook API v4.0.0 using php. Thank you

    Reply
    • Niraj Shah says:
      June 22, 2015 at 9:19 AM

      You can make an API call to me/groups (with the user logged in and `user_groups` permission). This will return a list of all the groups the user is a member of.

      Reply
      • tienluc says:
        June 22, 2015 at 5:00 PM

        Thank you so much. I did it but I encounter with another problem when I am trying to do 2 section. For example, I try to get group id and after that I want to use that ID to get post from that group. Is my idea possible?

      • Niraj Shah says:
        July 14, 2015 at 9:24 AM

        Once you have the Group IDs, you can loop through them and extract the posts using:

        /{group_id}/feed

        However, please note that Groups have been removed from the API in v2.4, and will no longer work from October 6, 2015.

  23. udayraj says:
    August 14, 2015 at 4:43 PM

    $request = new FacebookRequest(
    $session,
    ‘POST’,
    ‘/xxxxxxxxxxxxxxxxxxx/members/’.$_SESSION[‘FBID’],
    array(‘access_token’=>$token)
    );
    $response = $request->execute();
    $graphObject = $response->getGraphObject();
    /* handle the result */

    echo “”;
    print_r($request);
    echo “”;

    I have got this error and i had used GET and members=groups than get all data.

    Error look like –
    Fatal error: Uncaught exception ‘Facebook\FacebookAuthorizationException’ with message ‘(#3) Unknown method’ in

    Reply
    • Niraj Shah says:
      August 14, 2015 at 7:52 PM

      The error says that the API call you are making doesn’t exist – this is because you cannot POST to group_id/members. What happens if you make a GET call instead? And what exactly are you trying to do?

      Reply

Leave a Reply to abdulbaqueeCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

StackExchange / StackOverflow

profile for Niraj Shah on Stack Exchange, a network of free, community-driven Q&A sites

Support Me

Buy Me a Coffee

PSN Profile

Tags

ACL Amazon Amazon Web Services Android Android 4.4 KitKat Android 5.0 Lollipop Apache Backup Bug Command Line Cordova cPanel / WHM Facebook Facebook Graph API Facebook PHP SDK 4.0 Facebook Social Plugins Fan Page Firewall Flash Gadget Geolocation Google Nexus 5 Hacking HTML5 iOS JavaScript jQuery Laravel 5 Linux NodeJS Parse PDF PHP Plugin Portfolio PS4 Review Security Server SSH SSL Sysadmin Tutorial WordPress WordPress Plugins
© 2011-2025 Niraj Shah
  • Blog
  • Portfolio
  • WordPress
  • About Me
  • Contact Me
  • Privacy Policy
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Privacy Policy