Search code examples
facebook-graph-apipermissionsuser-location

Get User Home town And Current Location


I am using the following script from facebook example:

The script grabs the e-mail fine but hometown and location trigger a 500 error on my server. I need to grab the data for statistics.

<?php 

$app_id = "API_ID_GOES_HERE";
$app_secret = "SECRET_GOES_HERE";
$my_url = "REDIRECT_URL_GOES_HERE";
$permissions ="user_hometown,user_location,email";

session_start();
$code = $_REQUEST["code"];

if(empty($code)) {
 $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
 $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" 
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&scope=".$permissions. 
  "&state="
   . $_SESSION['state'];

 echo("<script> top.location.href='" . $dialog_url . "'</script>");
  }

if($_REQUEST['state'] == $_SESSION['state']) {
 $token_url = "https://graph.facebook.com/oauth/access_token?"
   . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
   . "&scope=".$permissions. "&client_secret=" . $app_secret . "&code=" . $code;

 $response = file_get_contents($token_url);
 $params = null;
 parse_str($response, $params);

 $graph_url = "https://graph.facebook.com/me?access_token=" 
   . $params['access_token'];

 $user = json_decode(file_get_contents($graph_url));

 echo("Hello " . $user->name);
 echo ("Location ". $user->location);


}
else {
  echo("The state does not match. You may be a victim of CSRF.");
}

?>

Solution

  • I found the answer. Using this $user->hometown->name Will get the Hometown array and the Name object.

    EX. [hometown] => stdClass Object ( [id] => 111806898837603 [name] => San Antonio, Texas )

    $user->hometown->name  
    

    OUTPUT:

    San Antonio, Texas