facebook graph api check if user is a member of a group using PHP

Zhia Aruza picture Zhia Aruza · May 1, 2012 · Viewed 8.8k times · Source

i want to check if a user is a member of a group using facebook graph api...

i have this:

$group = file_get_contents("https://graph.facebook.com/177129325652421/members?access_token=XXXXXXXX");
$group = json_decode($group);

$checkuser = $group->data;

and check the user if is a member by using his facebook id and in_array()

if(in_array($_GET["fid"],$checkuser)){

echo "yes";

} else {

echo "no";
}

can someone help me to correct this please... my code is not working...

Answer

xbonez picture xbonez · May 1, 2012

Reference: https://developers.facebook.com/docs/reference/api/

Use the API url:

https://graph.facebook.com/me/groups

To get a user's groups. In the above link, change the me/ to the user's FB ID. You must also pass in an Access Token.

The reply will be JSON encoded. Decode it using json_decode to a PHP Associative array. Iterate over it and check for the group you want.

The Graph API does not return all groups at once. You must either use the pagination links at the end of each response to fetch more, or use the limit parameter to request as many as you need.

The following code sample will post the IDs of the Groups you are a part of

<?php

$url = "https://graph.facebook.com/me/groups?access_token=AAAAAAITEghMBAMDc6iLFRSlVZCoWR0W3xVpEl1v7ZAxJRI3nh6X2GH0ZBDlrNMxupHXWfW5Tdy0jsrITfwnyfMhv2pNgXsVKkhHRoZC6dAZDZD";
$response = file_get_contents($url);

$obj = json_decode($response);

foreach($obj->data as $value) {
    echo $value->id;
    echo '<br>';
}

/* to check for existence of a particular group 

foreach($obj->data as $value) {
    if ($value->id == $yourID) {
        //found
        break;
    }

    //not found. fetch next page of groups
}

*/

PS - If running the above code gives you an error stating Could not find wrapper for "https", you need to uncomment/add the PHP extension extension=php_openssl.dll