My Programming Tutorials

My Programming Tutorials

Post into Facebook Page using PHP SDK v5

Last updated on by , 64 comments

In this article, we are going to learn how you can directly post into facebook page using PHP from your website or through your own platform.

There are lots of companies available on the Internet which provides such kind of services i.e. Hootsuite, Sproutsocial & Socialbakers etc.

Facebook always tries to motivate developers, to build such kind of modules facebook has provided its PHP library for PHP developers called Facebook SDK v5. This SDK is a library with powerful features that enable PHP developers to easily integrate Facebook login and make requests to the Graph API.

Post into Facebook Page using PHP Module

1. Create a Facebook App

1.1 – First we need to create a facebook app in order to use their API, sign in to your Facebook Developers account and click the “Add a New App” or “Get Started“(if you do not have a developers account) link.

1.2 – click on “Settings“, scroll down and you’ll see a “+ Add Platform” just click on it, now it will ask for your website URL, just put your website URL (URL where you want this module to be hosted on) into it.

1.3 – in “Settings” you will see the App ID copy it, we’ll need it further.

1.4 – again in “Settings” you will see the App Secret, to grab it you have to click on show button and have to enter your facebook password.

2. Installing the Facebook PHP SDK

2.1 – First we need to download the Facebook PHP SDK and upload it on your server (website URL, see 1.2), we just need to upload the Facebook directory.

2.2 – create an init.php file and paste below code into it, and replace APP_ID & APP_SECRET with your’s one (see 1.3 & 1.4).


session_start();

require_once('Facebook/autoload.php');

$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.9',
]);

3. The actual code for Post into Facebook Page using PHP

3.1 – create an index.php file, and paste below codes into it.


include('init.php');

$helper = $fb->getRedirectLoginHelper();

$permissions = ['manage_pages','publish_actions','publish_pages'];
$loginUrl = $helper->getLoginUrl('YOUR_WEBSITE_URL/fb-callback.php', $permissions);

echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';

replace “YOUR_WEBSITE_URL” in above code (website URL, see 1.2), as you can see in above code you have to create a fb-callback.php file.

In above code we have to set a callback URL (fb-callback.php), Facebook uses it to send back an access token. So go ahead and create a fb-callback.php file and paste below code into it.


include('init.php');

$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];

try {

  $accessToken = $helper->getAccessToken();

} catch(Facebook\Exceptions\FacebookResponseException $e) {

  echo 'Graph returned an error: ' . $e->getMessage();
  exit;

} catch(Facebook\Exceptions\FacebookSDKException $e) {
  
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;

}

if (! isset($accessToken)) {
  echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.';
  exit;
}

try {

  $response = $fb->get('me/accounts', $accessToken->getValue());
  $response = $response->getDecodedBody();

} catch(Facebook\Exceptions\FacebookResponseException $e) {
  
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;

} catch(Facebook\Exceptions\FacebookSDKException $e) {
  
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;

}

echo "<pre>";
print_r($response);
echo "</pre>";

As of now when we execute our index.php file you will see a “Log in with Facebook!” link there. When you click on that link you will be get redirected to a facebook page. This page asks a user to authorize our app, when they accept it they will get redirected to our fb-callback.php file, Facebook returns the list of all pages administrated by that user, which is stored in “$response” variable.

post into facebook page using php

as you can see above in screenshot, there is individual access_token & id (PageID) available for each page. Finally, these two credentials are required for posting stories on correspondence facebook page.

3.2 – now create a “post.php” file, and paste below codes into it


include('init.php');

$arr = array('message' => 'Testing Post for our new tutorial. Graph API.');

$res = $fb->post('PAGE_ID/feed/', $arr,	'ACCESS_TOKEN');

replace PAGE_ID & ACCESS_TOKEN with your page’s credentials as shown in above screenshot. By running the post.php file you will get something like below.

facebook php sdk

Check out our https://fbautomater.com Facebook Marketing Tool.

Hope you like post into facebook page using PHP module, please subscribe us to get latest updates and news. We are going to post lots of interesting articles in future, please like and share this article with your friends.

You may also like

Author Info

Paritosh Pandey

He loves Technology

Advertisement

64 responses to “Post into Facebook Page using PHP SDK v5”

  1. Anil Munde says:

    hi very good article thanks for sharing keep up the good work

  2. Aubrey says:

    This “solution using PHP” is a re-hash of what most developers already know unfortunately.
    I have a site that has multiple contributors and most of them are not very “tech savvy” to put it kindly.
    The site has a “Page” on FB and I need to post a share to THAT FB page automatically each time an article is published on the site by any contributor.
    The FB Page has been set up so that only the owner (me) can post to it to prevent all sorts of rubbish being posted and shared on the page.
    This solution DOES use PHP to do the posting BUT requires all sorts of user input which in my case is unfortunately a recipe for disaster.
    How would I go about doing that?
    BTW, this article was definitely one of the better ones for doing a user based share to Facebook – thanks.

    • Paritosh Pandey says:

      Hello @Aubrey,

      I think this is the article you’re searching for, I mean you just wanna automatic post to your FB Page when an article gets published. This article do perform such kinda operation.

      you just have to make some logics, i.e. setup this PHP script to gets automatically executed when an article gets published.

      If you find any problem, please feel free ask

      Thank you

    • JDev says:

      As a developer you must think

      Fb gives you a user id you could save that user id and only use that user to post things coming from your website

      A database is needed for this kind of task.

  3. Manos says:

    ‘Testing Post for our new tutorial. Graph API.’);
    $res = $fb->post(‘777777/feed/’, $arr, ‘trtrtrtrtrt’);
    ?>
    Doesn’t work!
    Any help please…

    • Paritosh Pandey says:

      Hello @manos,

      you supposed to elaborate your problem so that I can diagnost and suggest you appropriate solutions.

      Thank you

  4. Chris says:

    Great Article! Nice work!

  5. david says:

    Hi Paritosh,

    I am getting this error using this tut:

    “Graph returned an error: Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request”

    Any idea how I can fix it? Thanks for the help!

  6. Ismail says:

    hello,
    I am getting an error “Graph returned an error: Can not load URL: This URL domain is not included in application domains. To be able to upload this URL, please add all domains and subdomains of your app to the “Application domains” field in your app settings”

    I am running your code on my localhost.
    I have “http://localhost:80/facebook”
    in settings -> Basic -> App domains

    and I have the same “http://localhost:80/facebook” in Site Url.

    I have these urls “http://localhost:80/facebook/fb-callback.php” and “http://localhost:80/facebook/” in “Valid OAuth redirect URIs” under Products -> Facebook Login.

    • Ismail says:

      Never mind! I removed the port number from my URLs and it worked like a charm. Great post by the way. thumbs up for you.

    • Smith says:

      Hello, I actually get same error, I am running on my domain that already registered in app facebook but still get same error, how do i fix it ?

      Thanks

  7. thiru says:

    Fatal error: Uncaught exception ‘Facebook\Exceptions\FacebookAuthenticationException’ with message ‘Invalid OAuth access token.’ in /opt/lampp/htdocs/fb/Facebook/Exceptions/FacebookResponseException.php:106 Stack trace: #0 /opt/lampp/htdocs/fb/Facebook/FacebookResponse.php(210): Facebook\Exceptions\FacebookResponseException::create(Object(Facebook\FacebookResponse)) #1 /opt/lampp/htdocs/fb/Facebook/FacebookResponse.php(255): Facebook\FacebookResponse->makeException() #2 /opt/lampp/htdocs/fb/Facebook/FacebookResponse.php(82): Facebook\FacebookResponse->decodeBody() #3 /opt/lampp/htdocs/fb/Facebook/FacebookClient.php(225): Facebook\FacebookResponse->__construct(Object(Facebook\FacebookRequest), ‘{“error”:{“mess…’, 400, Array) #4 /opt/lampp/htdocs/fb/Facebook/Facebook.php(469): Facebook\FacebookClient->sendRequest(Object(Facebook\FacebookRequest)) #5 /opt/lampp/htdocs/fb/Facebook/Facebook.php(367): Facebook\Facebook->sendRequest(‘POST’, ‘145081993833901…’, Array, ‘ EAAD7wcKk6c8BA…’, NULL, NULL) #6 /opt/lampp/htdocs/fb/ in /opt/lampp/htdocs/fb/Facebook/Exceptions/FacebookResponseException.php on line 106

    • Paritosh Pandey says:

      It seems you are using it on localhost. Please see the step 1. you have to configure your script on Live server.

  8. weam osama says:

    it return empty array

  9. Stra Ioannis says:

    No OAuth data could be obtained from the signed request. User has not authorized your app yet.

    Thats my message on fb-callback.php page

    • Paritosh Pandey says:

      It is because user has not authorized your facebook app yet.

      see 3.1 to authorize app, you have to click on Log in with Facebook!

      I’m pretty sure you’d have done this before every application that kinda connected with facebook use this authorization step.

  10. Dan says:

    How can i add an image to my post?

    • Paritosh Pandey says:

      Hello @Dan,

      as described at facebook’s developer page, you can use following snippet.

      
      $data = [
        'message' => 'My awesome photo upload example.',
        'source' => $fb->fileToUpload('/path/to/photo.jpg'),
      ];
      
        $response = $fb->post('/me/photos', $data, '{access-token}');
      

      please do let us know whether it is working or not.

  11. shruti says:

    Hi Paritosh ,

    I have tried your code but getting error:

    Fatal error: Uncaught Facebook\Exceptions\FacebookAuthenticationException: Invalid appsecret_proof provided in the API argument in /home2/lifundig/public_html/facebook/Facebook/Exceptions/FacebookResponseException.php:106 Stack trace: #0 /home2/lifundig/public_html/facebook/Facebook/FacebookResponse.php(210): Facebook\Exceptions\FacebookResponseException::create(Object(Facebook\FacebookResponse)) #1 /home2/lifundig/public_html/facebook/Facebook/FacebookResponse.php(255): Facebook\FacebookResponse->makeException() #2 /home2/lifundig/public_html/facebook/Facebook/FacebookResponse.php(82): Facebook\FacebookResponse->decodeBody() #3 /home2/lifundig/public_html/facebook/Facebook/FacebookClient.php(224): Facebook\FacebookResponse->__construct(Object(Facebook\FacebookRequest), ‘{“error”:{“mess…’, 400, Array) #4 /home2/lifundig/public_html/facebook/Facebook/Facebook.php(469): Facebook\FacebookClient->sendRequest(Object(Facebook\FacebookRequest)) #5 /home2/lifundig/public_html/facebook/Facebook/Facebook.php(366): Facebook\Facebo in /home2/lifundig/public_html/facebook/Facebook/Exceptions/FacebookResponseException.php on line 106
    I have to test post.php direct?

    Thank you.

    Regards,
    shruti

    • Paritosh Pandey says:

      Hello @shruti,

      as per your error log in 2nd line it is clearly indicating that you have passed wrong appsecret credential, please refer to step 2 to fulfill this requirement.

  12. shruti says:

    hi paritosh,

    I have pass the secret key 75e73926131deb2de28a7c944758c528

    which I have copied from my developer app page??

  13. Paritosh Pandey says:

    hello @shruti,

    you’re not supposed to disclose your secret key, I recommend you to change your secret key.

    
    session_start();
    
    require_once('Facebook/autoload.php');
    
    $fb = new Facebook\Facebook([
    	'app_id' => 'APP_ID',
    	'app_secret' => 'APP_SECRET',
    	'default_graph_version' => 'v2.9',
    ]);
    

    APP_ID & APP_SECRET are the credentials which you can grab from Facbook’s developer page.

  14. shruti says:

    Hi Paritosh,

    I have changed my secret key and add into my code but still I am getting same error as above…

  15. Ivan says:

    Thank you so much Paritosh. I have been working on this for almost the whole day. Your article got me going in just 5 minutes.
    God bless you!

  16. Do we need to get that access token every time? I mean can we use the access token for future use?

  17. Afzaal Ashraf says:

    hi paritosh,

    i want to post on my facebook page,
    as per this code you are using an array

    $arr = array(‘message’=>’Test Post’);

    but i want to post multipple array values like:
    $arr = array
    (
    ‘message’ => array
    (
    “Name” => $Name
    // “Brand” => $Brand,
    ),

    );

    or

    $arr = array(‘message’=>$Name, ”message2 => $Brand);

    but i got error when i use my method, how to resolve it please help i will appreciate that.
    thanks in advance

    • Paritosh Pandey says:

      Hello @Afzaal,

      you can try loop approach to post multiple messages on a single page.

      if you find any difficulties, feel free to ask.

      Regards.

  18. love says:

    –post.php page
    ‘Testing Post for our new tutorial. Graph API.’);
    echo $res = $fb->post(‘605330756509914/feed/’, $arr, ‘ACCESS_TOKEN’);
    ?>
    —fb-callback.php page
    Array
    (
    [data] => Array
    (
    [0] => Array
    (
    [access_token] => ACCESS_TOKEN
    [category] => Web Designer
    [category_list] => Array
    (
    [0] => Array
    (
    [id] => 187393124625179
    [name] => Web Designer
    )

    )

    [name] => Lovetest
    [id] => 605330756509914
    [perms] => Array
    (
    [0] => ADMINISTER
    [1] => EDIT_PROFILE
    [2] => CREATE_CONTENT
    [3] => MODERATE_CONTENT
    [4] => CREATE_ADS
    [5] => BASIC_ADMIN
    )

    )

    )

    [paging] => Array
    (
    [cursors] => Array
    (
    [before] => NjA1MzMwNzU2NTA5OTE0
    [after] => NjA1MzMwNzU2NTA5OTE0
    )

    )

    )

    But message are not display on facebook page.

    • Paritosh Pandey says:

      First of all never disclose your ACCESS_TOKEN because it can risk your FB Account.

      please share the response after running the post.php file.

      • love says:

        Fatal error: Uncaught exception ‘Facebook\Exceptions\FacebookAuthorizationException’ with message ‘(#200) Requires either publish_actions permission, or manage_pages and publish_pages as an admin with sufficient administrative permission’ in /home/buynbag/public_html/facebook/api/Exceptions/FacebookResponseException.php:128 Stack trace: #0 /home/buynbag/public_html/facebook/api/FacebookResponse.php(210): Facebook\Exceptions\FacebookResponseException::create(Object(Facebook\FacebookResponse)) #1 /home/buynbag/public_html/facebook/api/FacebookResponse.php(255): Facebook\FacebookResponse->makeException() #2 /home/buynbag/public_html/facebook/api/FacebookResponse.php(82): Facebook\FacebookResponse->decodeBody() #3 /home/buynbag/public_html/facebook/api/FacebookClient.php(225): Facebook\FacebookResponse->__construct(Object(Facebook\FacebookRequest), ‘{“error”:{“mess…’, 403, Array) #4 /home/buynbag/public_html/facebook/api/Facebook.php(469): Facebook\FacebookClient->sendRequest(Object(Facebook\FacebookRequest)) #5 /home/buynb in /home/buynbag/public_html/facebook/api/Exceptions/FacebookResponseException.php on line 128

      • love says:

        post.php file after response Code Error

        Fatal error: Uncaught exception ‘Facebook\Exceptions\FacebookAuthorizationException’ with message ‘(#200) Requires either publish_actions permission, or manage_pages and publish_pages as an admin with sufficient administrative permission’ in /home/buynbag/public_html/facebook/api/Exceptions/FacebookResponseException.php:128 Stack trace: #0 /home/buynbag/public_html/facebook/api/FacebookResponse.php(210): Facebook\Exceptions\FacebookResponseException::create(Object(Facebook\FacebookResponse)) #1 /home/buynbag/public_html/facebook/api/FacebookResponse.php(255): Facebook\FacebookResponse->makeException() #2 /home/buynbag/public_html/facebook/api/FacebookResponse.php(82): Facebook\FacebookResponse->decodeBody() #3 /home/buynbag/public_html/facebook/api/FacebookClient.php(225): Facebook\FacebookResponse->__construct(Object(Facebook\FacebookRequest), ‘{“error”:{“mess…’, 403, Array) #4 /home/buynbag/public_html/facebook/api/Facebook.php(469): Facebook\FacebookClient->sendRequest(Object(Facebook\FacebookRequest)) #5 /home/buynb in /home/buynbag/public_html/facebook/api/Exceptions/FacebookResponseException.php on line 128

        • Paritosh Pandey says:

          it seems you’ve not authorized your Facebook App properly to post contents.

          try with creating a new Facebook App, and click Log in with Facebook! and authorize app properly.

  19. love says:

    Fatal error: Uncaught exception ‘Facebook\Exceptions\FacebookAuthorizationException’ with message ‘(#200) Requires either publish_actions permission, or manage_pages and publish_pages as an admin with sufficient administrative permission’ in /home/buynbag/public_html/facebook/api/Exceptions/FacebookResponseException.php:128 Stack trace: #0 /home/buynbag/public_html/facebook/api/FacebookResponse.php(210): Facebook\Exceptions\FacebookResponseException::create(Object(Facebook\FacebookResponse)) #1 /home/buynbag/public_html/facebook/api/FacebookResponse.php(255): Facebook\FacebookResponse->makeException() #2 /home/buynbag/public_html/facebook/api/FacebookResponse.php(82): Facebook\FacebookResponse->decodeBody() #3 /home/buynbag/public_html/facebook/api/FacebookClient.php(225): Facebook\FacebookResponse->__construct(Object(Facebook\FacebookRequest), ‘{“error”:{“mess…’, 403, Array) #4 /home/buynbag/public_html/facebook/api/Facebook.php(469): Facebook\FacebookClient->sendRequest(Object(Facebook\FacebookRequest)) #5 /home/buynb in /home/buynbag/public_html/facebook/api/Exceptions/FacebookResponseException.php on line 128

  20. Manish says:

    Hi,

    I have used this tutorial to implement facebook login button. Everything setup as you mentioned.

    Getting “Domain not add it in app” error message. Why its happen ?

    Thanks

    • Paritosh Pandey says:

      in Facebook Developer (Setting >> Basic), there would be an input box for “App Domains”, fill this as well.

  21. Ting says:

    Hi,
    1. Invalid Scopes: manage_pages, publish_pages. This message is only shown to developers. Maybe it need app review from facebook, so I just changed it to email and get the access token from explorer but the problem no 2 happens.
    2. currently unable to handle this request for post.php.

    Could you please help?

    Thanks in advance.

    • Paritosh Pandey says:

      manage_pages & publish_pages permissions are responsible for posting contents on facebook.

      The publish_actions permission has been removed. Apps that have already been approved for publish_actions can continue using the permission until August 1st, 2018. If you want to provide a way for your app users to share content to Facebook and Instagram beyond this date, I encourage you to use Facebook’s Sharing products instead.

  22. Steve Guluk says:

    Hello,
    Thanks for the tutorial…

    Everything made sense and worked fine until executing the post.php page. The response is a “Duplicate status message..”

    Any idea what could cause this or what values should be echoed to trace the problem?

    Fatal error: Uncaught exception ‘Facebook\Exceptions\FacebookClientException’ with message ‘Duplicate status message’ in E:…..php-graph-sdk-5.x\src\Facebook\Exceptions\FacebookResponseException.php:123 Stack trace: #0….

  23. Apartamenti says:

    Very good article. Is there any limit for posts ?

    Thanks.

    • Paritosh Pandey says:

      there is no any limit for post, but there is a limit on how frequently you are posting. Facebook doesn’t like spams, if they find you are spreading spams they gonna block your account.

  24. jelo says:

    Good day. Back on your step 2 where can I upload my FACEBOOK DIRECTORY file ? I already downloaded the Facebook SDK.

    Thanks for the help.

  25. Toi says:

    Hi,

    (#200) Requires either publish_to_groups permission and app being installed in the group, or manage_pages and publish_pages as an admin with sufficient administrative permission

    Could you please help?

    Thanks

    • krupali says:

      Hello,

      Have you got solution of this error regarding posting to facebook?

      Please help me if you find any solution, because I’m getting such type of error again and again.

      And currently my facebook app is in development mode.

  26. Uriel Albarran says:

    Don’t know if this code it’s still valid but here’s my problem, I keep getting getting the error about the don’t have white listed my domain on the domains app: my domain it’s https://live.domain.com/ and I already put that on domain apps and also on the web platform url, but still have the issue, there’s something that i’m missing? I follow step by step the tutorial, and don’t know if I need to add :443/ after the url, it’s because it’s a sub-domain? or what i’m really frustrated

    • Paritosh Pandey says:

      You should try with your main domain, ie. domain.com

      , although this article is too old, I do not recommended to use it, I’ll try my best to publish a new version of it soon.

      Regards,

  27. Bironk says:

    Hi, thanks for the tutorial.
    my questions, 1.How to get the response code to verify whether the post has been successfully posted or not.
    2. How to create ‘message’ with url link in it?

  28. Sipin says:

    WHERE do we get the page_id please

    • Paritosh Pandey says:

      page id is a string after facebook.com/. i.e.
      https://www.facebook.com/myprogrammingtutorials here myprogrammingtutorials is my page id, page id could be autogenerated integers by default

  29. Yogesh sharma says:

    Hello,

    Would to publish the one post for “How to share the text or image to whatsapp via Php or Codeigniter.

    Thanks
    Regards
    Yogesh

  30. I got this website from my friend who informed me concerning this site and at
    the moment this time I am visiting this website and reading very informative content at this place.

  31. Hello to every single one, it’s truly a pleasant for me to
    pay a visit this website, it consists of precious Information.

  32. Taras says:

    Hello. As I understood, posting news on Timeline or News Feed it’s deprecated, and now available posting only on Page (if you or someone have it),
    AM I RIGHT?

  33. Taras says:

    Maybe someone knows how intsagramm makes autoposting on timeline and my history?

  34. tmgreed says:

    OH BOI, FINALLY

    I was trying to Post on facebook for days, you (and this guy here https://docs.listingprowp.com/knowledgebase/how-to-enable-the-social-media-login/) saved me!

  35. Tom Dings says:

    Very nice explanation. It is not new for me but it is always nice to read a story written by someone else in another way. Just to see the differences.

    Many thanks and enjoy your weekend!

Leave a Reply

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