Why is getSessionFromRedirect() return a NULL?

SBel picture SBel · May 7, 2014 · Viewed 14.4k times · Source

I have the following code which redirects the user to log into facebook and tries to retrieve the session but the session is NULL:

<?php

session_start();

require 'vendor/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;

FacebookSession::setDefaultApplication('Foo', 'Bar');

$helper = new FacebookRedirectLoginHelper('Baz');
$loginUrl = $helper->getLoginUrl();  

echo '<a href="' . $loginUrl . '">Log In</a>';  

$session = $helper->getSessionFromRedirect();  

// This displays [NULL] always
echo '[' . gettype($session) . ']';

?>

I don't understand why the $session is always NULL. Please help.

Answer

bhushya picture bhushya · Jul 16, 2014

It happens because of the getLoginUrl() function,

because when we mentioned same page as FB redirect page, it call getLoginUrl() function again and again.. which change $this->state variable value

and then isValidRedirect() and getSessionFromRedirect() always return null

Here is solution to use same page as FB redirection page:

Don't call getLoginUrl() when facebook redirect you to same page, just add the proper session check to check valid facebook session (Please refer following code example)

session_start();
require("facebook/autoload.php");


use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

FacebookSession::setDefaultApplication('appid84', '0secret0a626c6');

$helper = new FacebookRedirectLoginHelper('http://tmd.local/fblogin.php');

try {
  $session = $helper->getSessionFromRedirect();
  // var_dump($session);
} catch(FacebookRequestException $ex) {
} catch(\Exception $ex) {
}
if ($session) {
  var_dump($session);
}
else
{
  $loginUrl = $helper->getLoginUrl();
  header("location:".$loginUrl);
  exit;
}