March 1, 2024 5:02 am

How to post into a Facebook Page with PHP using Graph API

We have published one article on How to publish status on Facebook with Graph API which post status on user’s wall when user write , now I am going to show how to post status on pages to post status on Facebook page we use Facebook Graph API in PHP to perform this task.

How to post into a Facebook Page with PHP using Graph API

[wpdm_file id=67]DEMO

To create Facebook application follow instruction on my previous post How to Login with Facebook Graph API in PHP

Script contains two folders called src and images with PHP files.

src

– base_facebook.php // Class Get user Information.

– facebook.php // Class Get user Information.

– config.php // Configuration file.

images

index.php // Main index file.

PHP Code

Edit config.php

<?php

$config['callback_url']         =   'CALL BACK URL/?fbTrue=true'; //   /?fbTrue=true allow you to code process section.

//Facebook configuration
$config['App_ID']      =   'Your App ID';
$config['App_Secret']  =   'Your App Secret'; 

?>

On the main page show you one button for connect with PHP on redirect to Facebook it will ask you for permission here we add one more permission which is manage_pages with this permission you will allow that application to manage your pages.

index.php

<?php
session_start();
require 'src/config.php';
require 'src/facebook.php';
require 'db.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => $config['App_ID'],
  'secret' => $config['App_Secret'],
  'cookie' => true
));

if(isset($_POST['status']))
{
    $page = split("-",$_POST['page']);
    $page_token = $page[0];
    $page_id= $page[1];
    // status with link
    $publish = $facebook->api('/'.$page_id.'/feed', 'post',
            array('access_token' => $page_token,
            'message'=> $_POST['status'],
            'from' => $config['App_ID'],
            'to' => $page_id,
            'caption' => 'Caption',
            'name' => 'Name',
            'link' => 'http://www.example.com/',
            'picture' => 'https://www.phpgang.com/wp-content/themes/PHPGang_v2/img/logo.png',
            'description' => $_POST['status'].' via demo.PHPGang.com'
            ));
    //Simple status without link

    //$publish = $facebook->api('/'.$page_id.'/feed', 'post',
//        array('access_token' => $page_token,'message'=>$_POST['status'] .'   via PHPGang.com Demo',
//        'from' => $config['App_ID']
//        ));

    echo 'Status updated.<br>';
    $graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
    $pages = json_decode(file_get_contents($graph_url_pages)); // get all pages information from above url.
    $dropdown = "";
    for($i=0;$i<count($pages->data);$i++)
    {
        $dropdown .= "<option value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."</option>";
    }

    echo '
    <style>
    #status
    {
        width: 357px;
        height: 28px;
        font-size: 15px;
    }
    </style>
    '.$message.'
    <form action="index.php" method="post">
    Select Page on which you want to post status: <br><select name="page" id=status>'.$dropdown.'</select><br><br>
    <input type="text" name="status" id="status" placeholder="Write a comment...." /><input type="submit" value="Post On My Page!" style="padding: 5px;" />
    <form>';

}
elseif(isset($_GET['fbTrue']))
{
    $token_url = "https://graph.facebook.com/oauth/access_token?"
        . "client_id=".$config['App_ID']."&redirect_uri=" . urlencode($config['callback_url'])
        . "&client_secret=".$config['App_Secret']."&code=" . $_GET['code'];

    $response = file_get_contents($token_url);   // get access token from url
    $params = null;
    parse_str($response, $params);

    $_SESSION['token'] = $params['access_token'];

    $graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
    $pages = json_decode(file_get_contents($graph_url_pages)); // get all pages information from above url.
    $dropdown = "";
    for($i=0;$i<count($pages->data);$i++)
    {
        $dropdown .= "<option value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."</option>";
    }

    echo '
    <style>
    #status
    {
        width: 357px;
        height: 28px;
        font-size: 15px;
    }
    </style>
    '.$message.'
    <form action="index.php" method="post">
    Select Page on which you want to post status: <br><select name="page" id=status>'.$dropdown.'</select><br><br>
    <input type="text" name="status" id="status" placeholder="Write a comment...." /><input type="submit" value="Post On My Page!" style="padding: 5px;" />
    <form>';    
}
else
{
    echo 'Connect &nbsp;&nbsp;<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_about_me,offline_access,publish_stream,publish_actions,manage_pages"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>';
}
?>

Explanation of above code:

We will call this URL to get Facebook profile token.

https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_about_me,offline_access,publish_stream,publish_actions,manage_pages

On callback page it will give you a code parameter using that code you will call this URL in backhand and get access token.

$token_url = "https://graph.facebook.com/oauth/access_token?"
        . "client_id=".$config['App_ID']."&redirect_uri=" . urlencode($config['callback_url'])
        . "&client_secret=".$config['App_Secret']."&code=" . $_GET['code'];

$response = file_get_contents($token_url);   // get access token from url
$params = null;
parse_str($response, $params);

After that we got the access token of that user with manage pages permission in $response variable.

Now use that token and get all pages under that user account and their access tocke.

$graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
$pages = json_decode(file_get_contents($graph_url_pages)); // get all pages information from above url.

facebook-page-tocken-phpgang

This page show you all pages token and page name and id’s in demo we show dropdown of pages you can select any page and add status in text box and publish it will publish it on your page.

Create a drop down from above json code is very simple and easy here is the snippet for that.

$dropdown = "";
for($i=0;$i<count($pages->data);$i++)
{
   $dropdown .= "".$pages->data[$i]->name."";
}
$dropdown .= "Select Page on which you want to post status:
";

Status Publish Code

There is 2 code snippet one can share link on page with custom image and description like blow:

$publish = $facebook->api('/'.$page_id.'/feed', 'post',
            array('access_token' => $page_token,
            'message'=> 'Testing',
            'from' => $config['App_ID'],
            'to' => $page_id,
            'caption' => 'PHP Gang',
            'name' => 'PHP Gang',
            'link' => 'https://www.phpgang.com/',
            'picture' => 'https://www.phpgang.com/wp-content/themes/PHPGang_v2/img/logo.png',
            'description' => 'Testing with PHPGang.com Demo'
            ));

The above code can share a link like this screenshot:

link-share-on-facebook-page

2nd snippet of sharing which only share your text on the page and if you include any link it will extract that link itself and show title image and description.

$publish = $facebook->api('/'.$page_id.'/feed', 'post',
array('access_token' => $page_token,'message'=>$_POST['status'] .'   via PHPGang.com Demo',
'from' => $config['App_ID']
));

Screenshot of status posted by above snippet:

simple-status-share-on-facebook-page

 This is the simple scenario of posting on Facebook pages I hope you like this tutorial so please give your feedback in comments.

[wpdm_file id=67]DEMO

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

76 responses to “How to post into a Facebook Page with PHP using Graph API”

  1. Lokesh Sharma says:

    hello sir after login my page is not redircting

  2. shojol80 says:

    thank you sir,,its working fine,,but i want to delete some post after few moments,,is it possible to delete any post using there API??

  3. 555|STi says:

    Can’t download script. =/ I’m already subscribed with 2 email addresses.

  4. srinuchilukuri says:

    Hi huzoorbux sir,

    using Facebook graph API to post links into my Facebook page. From yesterday on wards I am getting ‘Use App’ button with each post feed.

    how to remove “Use App” button
    please find the screenshoot.

  5. mayank says:

    no link found for downloading

  6. Marcos Trama says:

    Good article!
    I’m having a problem when i post the link. When i use the ‘link’ field, the post is made with my user (owner of the page). When i dont use the ‘link’ field, the post is made as the page, but i get no link to my website. Do you know what this happens? thanks a lot

  7. Chakrimela com says:

    My posts are posting. But only i can see the post when i log in as admin but can not see the post while i ma not logged as admin, means outside users are unable to see.

    Please advise solution.

  8. Kiran says:

    Hi .. Nice tutorials !
    I was looking for same stuffs to integrate in my website.. But little change is I want to post comments in to users profile instead page.. I have goggled but what i found is not working here. Pls Kindly suggest me asap..

  9. Dave says:

    6 hours to download a crappy script that has laready shown a huge amount of error in your own Demo! lol fuck off and remove my email from your mailing list asap. I’ve already spam listed your email so don’t botehr to send me anything anyway. idiots.

  10. niko says:

    Now this is old example. How can we do with facebook php sdk version 4.0.9?

  11. arpita says:

    nice tutorial but not downlodable.. i subscribe your policy then n then not download..plzzz send me mail on this email [email protected]

  12. huzoorbux says:

    Might be file_get_contents not allowed on your hosting you try to curl file get content from here: https://www.phpgang.com/replace-file_get_contentsfopen-with-curl_30.html

  13. Gurubaksh says:

    Please anyone tell me how to get publish steam permission i am using this
    define(“PERMISSIONS”, “publish_stream,email,user_about_me,user_birthday,user_website “);

    $loginURL = $facebook->getLoginUrl(array( “scope” => PERMISSIONS, ‘redirect_uri’ => REDIRECT_URL));

    But all time facebook ignore my PERMISSIONS

    • huzoorbux says:

      You need to send request to facebook to review your application permission and allow your app for these permissions https://developers.facebook.com/docs/apps/review.

      • Gurubaksh says:

        Thanks huzoorbux,

        huzoorbux, I have send request two times to facebook but still i did not get any reply form them, Will they Email me. And One question how long should I wait for reply.

        • huzoorbux says:

          The review time estimate will range between 3 to 7 business days.

          • Gurubaksh says:

            Thanks I will wait till that time, Thanks for your help. I will keep in touch with your for more help

          • Gurubaksh says:

            Dear Sir,

            Already 6 days has gone but still I do not get permissions in my account. Please suggest me what to do. Sir Please give the exact link for fill up to contact facebook. I have missed the out the link what I used last time. Please give the exact link. I am not finding it.

  14. Vikas says:

    Is this works for graph api v2.1 ?

  15. vikas says:

    Notice: Undefined variable: message in index.php on line 90 . Have you changed the source code ?as I am getting above error after facebook login .

  16. Nilesh Daldra says:

    where can i find facebook.php and base_facebook.php files?????

  17. Tommy Rah says:

    Demo is not working .
    Fatal error: Uncaught OAuthException: (#200) Permissions error
    thrown in
    /hermes/waloraweb002/b2497/pow.huzoorbuxcom/htdocs/phpgang/demo/post-into-a-facebook-page-with-php-using-graph-api/src/base_facebook.php
    on line 1243

  18. Ajith says:

    Hi,
    Your code is working . This code only working in Main app created user account. I mean the the main page admin can list all pages. But the sub admin users can’t access the pages. Is it any issue in my app..
    Please help me for this issue

  19. vfgvfgvbgfv says:

    grrgvfc

  20. mukund says:

    Latest Api is not Support this Code..So Plz put Latest Api code….

  21. kailashkumar says:

    I was successfully paste the folder in my online server.
    But, i got following error:

    Given URL is not permitted by the Application configuration: One or more
    of the given URLs is not permitted by the App’s settings. It must match
    the Website URL or Canvas URL, or the domain must be a subdomain of one
    of the App’s domains.

  22. q-think the welcome says:

    Nice,
    But, How I can Download your this code?
    I have subscribe your Feed but still can’t download?

    Please help,,,thanks

  23. Mehul Kumbhani says:

    Hi,

    It is working fine but i have one issue..

    When i am posting it is showing like i have posted to my page.

    Like ::: — “My Name -> My Page Name”
    But i wanted it to show like my page has posted that post on the page timeline.

    I tried specifing “from” param also but still it is posting as same.
    Sir, plz guide me what i am missing.

  24. Parvez says:

    When i use this code and run it after login it give error like this: Fatal error: Uncaught OAuthException: (#200) Permissions error
    thrown in /home/websocialite/public_html/post-to-fb-wall/src/base_facebook.php on line 1243

  25. Naiyar Azam says:

    thanks

  26. michael says:

    it’s not show me my page… the select tag is null

  27. Vivek says:

    My select tag is null even if i have 5 pages in my account. Please give me solution.

  28. Vivek says:

    Can i post multiple image in single post using this same demo….?? If yes, then how please ??

  29. khubbab says:

    Hi script cannot be downloaded do you have newer version or can you send me the script at [email protected]

  30. Van Muoi says:

    Hi script can’t working. Check it, please. Thanks.

  31. Komal Garg says:

    hii can u please send me the code to auto share post on fb at [email protected]
    Thanks in advance

  32. Hoang Hung says:

    Not found select fanpage

  33. Shaan Ansari says:

    My client need his facebook post on website is their any api

  34. Santosh Khatri says:

    hi Huzoor Bux, Very nice tutorial and i am using your code but can you tell me how to show full width image using /feed. it is showing in thumbnail image not in full width. if i use /photos then it can not use parameters like url, name, description.

  35. bunthan prak says:

    Can not download source code:

    /var/www/html/wp-content/plugins/download-manager/cache/ must have to be writable!

    If possible could you please send me the full source code to my email: [email protected]

    Thanks in advance!

  36. Parnika Ananth says:

    I was trying to make subscribe to your site but not able to subscribe. please check it and i want to this download code. it is very helpful and nice tutorial… please send to me at [email protected]

  37. Vikul Gupta says:

    Hi

    I am not able to download .

    Can u please email me the source code at [email protected]

  38. Ibnu Qoyyim Alfath says:

    Hello sir,
    Nice tutorial, but can u please email me the source code at [email protected]

  39. Lamp T ana M says:

    Hello ,

    I am not able to download this code. Can you please send this code on my email : [email protected]

  40. Aradhya Sharma says:

    i7rtygyug

  41. Niyas Ali says:

    can you pleae send this code to [email protected]

  42. Rashmi Attarde says:

    please send me code on
    [email protected]

Leave a Reply

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