August 19, 2014 2:11 pm

How to Post Into Facebook Group with PHP using Graph API

Hey guyz I received many requests from my readers to write tutorial on facebook Group status update so I am going to show you that how you can do update your joined groups. You can joined many groups and update your status on groups to promote your websites or your products on all groups and this is an easy way to promotion.

post into a Facebook Page with PHP using Graph API

[wpdm_file id=110]DEMO

How to integrate:

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

We need permissions publish_actions, user_groups to run this code on your website. You need to send request to facebook to review your application permission and allow your app for these permissions Read more.

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'; 

?>

First of all we get current user’s joined groups list and display in drop down.

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

Now we have all joined groups list in $dropdown variable.

Posting on Group is simply like we make post on facebook page in our previous tutorial How to post into a Facebook Page with PHP using Graph API below is the code for posting.

Publish Link with Image:

$publish = $facebook->api('/'.$group_id.'/feed', 'post',
            array('access_token' => $_SESSION['token'],
            'message'=> 'Testing',
            'from' => $config['App_ID'],
            'to' => $group_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'
            ));

Above code post on facebook group a link with image see attached image.

Post on facebook group

Publish text status only only:

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

Above code share only text status on your selected group.

Post text status on facebook group

Here is my complete code to get user authentication and post status:

<?php
session_start();
require 'src/config.php';
require 'src/facebook.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']))
{
    $group_id = $_POST['group'];
    
    $publish = $facebook->api('/'.$group_id.'/feed', 'post',
            array('access_token' => $_SESSION['token'],
            'message'=> 'Testing',
            'from' => $config['App_ID'],
            'to' => $group_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'
            ));
        $publish = $facebook->api('/'.$group_id.'/feed', 'post',
        array('access_token' => $_SESSION['token'],'message'=>$_POST['status'] .'   via PHPGang.com Demo',
        'from' => $config['App_ID']
        ));
        $message = 'Status updated.<br>';
        $graph_url_groups = "https://graph.facebook.com/v2.1/me/groups?access_token=".$_SESSION['token'];

    $groups = json_decode(file_get_contents_curl($graph_url_groups)); // get all groups information from above url.
   
    $dropdown = "";
    for($i=0;$i<count($groups->data);$i++)
    {
        $dropdown .= "<option value='".$groups->data[$i]->access_token."-".$groups->data[$i]->id."'>".$groups->data[$i]->name."</option>";
    }
    
    $content = '
    <style>
    #status
    {
        width: 357px;
        height: 28px;
        font-size: 15px;
    }
    </style>
    '.$message.'
    <form action="index.php" method="post">
    Select Group on which you want to post status: <br><select name="group" id="status">'.$dropdown.'</select><br><br>
    <input type="text" name="status" id="status" placeholder="Write a comment...." />
    <input type="submit" value="Post On My Group!" style="padding: 5px;" />
    <form>';
}
elseif(isset($_GET['fbTrue']))
{
    $token_url = "https://graph.facebook.com/v2.1/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_curl($token_url);   // get access token from url
    $params = null;
    parse_str($response, $params);

    $graph_url = "https://graph.facebook.com/v2.1/me?access_token=" 
        . $params['access_token'];
        $_SESSION['token'] = $params['access_token'];
    $user = json_decode(file_get_contents_curl($graph_url)); // Get user information from given url
    
    
    $graph_url_groups = "https://graph.facebook.com/v2.1/me/groups?access_token=".$_SESSION['token'];
    $groups = json_decode(file_get_contents_curl($graph_url_groups)); // get all groups information from above url.
   
    
    $dropdown = "";
    for($i=0;$i<count($groups->data);$i++)
    {
        $dropdown .= "<option value='".$groups->data[$i]->id."'>".$groups->data[$i]->name."</option>";
    }
    
    $content = '
    <style>
    #status
    {
        width: 357px;
        height: 28px;
        font-size: 15px;
    }
    </style>
    '.$message.'
    <form action="index.php" method="post">
    Select Group on which you want to post status: <br><select name="group" id=status>'.$dropdown.'</select><br><br>
    <input type="text" name="status" id="status" placeholder="Write a comment...." />
    <input type="submit" value="Post On My Group!" style="padding: 5px;" />
    <form>';
}
else
{
    $content = '<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,publish_stream,publish_actions,user_groups"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>';
}

echo $content; 

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
?>

Above code first of all authenticate you permission from facebook and then show a form with a drop down and a text box to select group and status to update.

In my script you can post on one group at 1 time but if you want to post on all groups in one click you can modify script and do it easily.

You can can make change and create a auto facebook group posting application.

[wpdm_file id=110]DEMO

That’s all for this tutorial hope you guyz like this tutorial please feel free to comment below.

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:

38 responses to “How to Post Into Facebook Group with PHP using Graph API”

  1. URAGANU . says:

    Thank you for this tutorial.
    Until now I succeeded to extract the feed from a Facebook Group and include it in a Android App using appyet.com. Now all the feeds display on the phone and I don’t have to keep facebook app open.
    When they will upgrade their templates and allow php scripts to run I will implement this into same application to have a fully operational Facebook Group Application :D.

    Thank you one more time, this resource is priceless.

    • Lilesh Jadav says:

      but facebook feed needs login into facebook acc. and how can you login facebook into appyet app ??

  2. tag says:

    I cannot download the source code. I’m already subscribed to the mailing list .But can’t download can you please email me a sourcecode.

  3. ajay dubey says:

    i need you help when i download code then its work fine only 1 issue is their can u suggest me how i can fetch group account to user login

  4. ajay dubey says:

    now its working with single user onlt its get single user group

  5. ajay dubey says:

    hello

  6. ajay dubey says:

    anybody here

  7. ajay dubey says:

    anybody can help me

  8. Đặng Đình Sơn says:

    code not working it’s not load group

  9. Đặng Đình Sơn says:

    Please help me for a trouble ?
    It’s not show scope when user access apps.
    sorry for my English

  10. Đảo Hoang says:

    hello. i can’t download code. please help me

  11. ashishrevar says:

    Hello there,
    I need to publish link on all my groups. I set sleep(10) after every post. I am getting below listed error.
    What to do?
    Fatal error: Uncaught FacebookApiException: Permissions error thrown in /home/storyreads/storyreads.com/fb/base_facebook.php on line 1325

  12. Trần Tiến Lực says:

    Hello.
    I did as in your tutorial but it does not work. Could you please help me. This is my error

    “The parameter app_id is required”

    I think that the problem is my facebook app, but I can not fix it. Please help me Thank you!

  13. Bert says:

    Hello Dont show my groups

  14. sun vichea says:

    can you tell me about auto post in all group ?

  15. sanaullah says:

    Sr agr ap kahty hu tu username and password b dy dyta hu par plz sr mari help karo

  16. sunny says:

    The redirect_uri URL must be absolute im having these error

  17. sanaullah says:

    Sr this is error plz solve my problem plz sr.first time join this site plz help me

  18. sanaullah says:

    Sr kun kun sy items select karny is group posting ky lye.

  19. Trần Lý Như says:

    demo is not working. i can’t choose Group

  20. Mêồʬ ḿėẘ says:

    The redirect_uri URL must be absolute im having these error

  21. arvind says:

    Please Help me in this.

  22. Marcello Patto says:

    I got the error “The parameter app_id is required”. I have the app_id nad secret number as well, but, there´s something wrong… have you testing the script latelly? Have you an update or something?
    Thks a lot from Brazil!

  23. Marcello Patto says:

    I got the error “The parameter app_id is required”. I have the app_id nad secret number as well, but, there´s something wrong… have you testing the script latelly? Have you an update or something?
    Thks a lot from Brazil!

  24. ManiKanth Vanka says:

    I need this to be implemented using javascript only.Is it possible?If yes do help bro.
    Regards

  25. John Kerim says:

    i can’t sub and download?

  26. BralachCodex says:

    Fatal error: Uncaught Error: Call to a member function api() on null in D:0.Serverwww0.WebTestingFacebook.Api.Groupefacebook.php:14 Stack trace: #0 D:0.Serverwww0.WebTestingFacebook.Api.Groupeindex.php(5): require() #1 {main} thrown in

  27. dominatos says:

    Is this manual actual for nowadays?

  28. Atif Ali Khan says:

    Hi,
    The demo is showing the error. I think the api has changed now. Will you please write an article about the new API of the Facebook sharing in the groups?

Leave a Reply

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