the code is according to fb manual, and i ve noticed that if the user refreshes the page, i can't retrieve the id of the user..the user will need to clear from the address bar the entire string after my url, in order to be able to obtain user info..
<?php
$app_id = "myid";
$app_secret = "mysecretkey";
$my_url = "http://myurl.php";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=publish_actions";
header("Location: " . $dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$_SESSION['access_token'] = $params['access_token'];
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo var_dump($user);
else {
echo("The state does not match. You may be a victim of CSRF.");
}
var_dump returns to me all necessary information after first redirect, but if i refresh the page it returns null.. perhaps i need to "destroy" any session cookies??
This happens cause the $code
that you are using is no longer valid and has been consumed.
Also might I suggest you to use Facebook's PHP SDK . It would reduce time to develop your app and take care of these errors for you.
i altered the code a little bit, in order to by pass the problem..
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
if ($params['access_token'] == NULL) {
header("Location: " . $my_url);
}
$user = json_decode(file_get_contents($graph_url));
}
so, if the access_token is not valid, then the page is "forced" to be reloaded without any string query and retrieves a new one.. :) there was a usefull reference over here as well https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/ and many thanks to @Anvesh Saxena for his contribution
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.