Why is getSessionFromRedirect() return a NULL?

2019-01-14 12:38发布

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.

8条回答
对你真心纯属浪费
2楼-- · 2019-01-14 13:23

What made the real difference to me was the redirect Url address i was using. Hours and hours because of a slash.

Explaining with examples:

(Wrong)

$helper = new FacebookRedirectLoginHelper('http://www.example.com');

(Right)

$helper = new FacebookRedirectLoginHelper('http://www.example.com/');

I've read a ton of tutorials and answers on Stackoverflow and this final slash was the real answer. I hope it helps someone

查看更多
Evening l夕情丶
3楼-- · 2019-01-14 13:31

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;
}
查看更多
登录 后发表回答