Question

I'm trying to use php to access and collect basic information on-

users name, gender, birthday, age_range etc.

but for some reason I can only get the name and gender to work and I get an Undefined index: with birthday and age_range.

Can someone help me figure this out? I am new to Facebook Graph API and trying to modify the given code they gave for logging. I think I don't need an access token yet because I'm trying to get the initial permissions when they log into the site.

<?php
include('src\facebook.php');

//$scope = 'username,age_range,birthday,gender';

$config = array(
      'appId'              => 'XXXXXXXXXXXXXXXX',
      'secret'             => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      'fileUpload'         => false, 
      'allowSignedRequest' => false 
    );

  $facebook = new Facebook($config);
  $user_id = $facebook->getUser();
?>
<html>
  <head></head>
  <body>

  <?php
    if($user_id) {
      try {
            //$user_profile = $facebook->api('/me','GET');
            $user_profile = $facebook->api('/me','GET', array('scope' => 'user_birthday,gender,age_range,name,likes'));
            echo "Name: " .     $user_profile['name'];
            echo " Gender: " . $user_profile['gender'];
            echo " DOB: " .    $user_profile['birthday'];
            echo " Age_Range: " .    $user_profile['age_range'];
      } catch(FacebookApiException $e) {
            $login_url = $facebook->getLoginUrl(); 
            echo 'Please <a href="' . $login_url . '">login.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
      }   
    } else {
      // No user, print a link for the user to login
      $login_url = $facebook->getLoginUrl();
      echo 'Please <a href="' . $login_url . '">login.</a>';
    }
  ?>

  </body>
</html>

Also could someone explain to how to get user likes, I know I have to specify user permission using the Facebook->api(me/like) but then how do I access the array? Thanks for the help!

Was it helpful?

Solution

Please follow only the official docs to avoid such mistakes-

  1. You are adding the permissions scope into the wrong place.

  2. You are using the wrong permissions: gender,age_range,name,likes - these are not valid permissions!

    Permissions that you require are: user_likes (for likes), user_birthday(for birthday); rest are the part of the basic(default) permissions only!

    The age range field is also included in the public profile- for anyone who installs your app.

You have to add the scope parameter while using the login code: getLoginUrl().

$params = array(
  'scope' => 'user_likes, user_birthday'
);
$loginUrl = $facebook->getLoginUrl($params);

After the user successfully grants the permissions, you'll get the required things!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top