首先让我们来看看两个文件:
index.php
<?php session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf=8" />
<title>FB App</title>
</head>
<body>
<?php
define( 'FACEBOOK_SDK_V4_SRC_DIR', 'src/Facebook/');
require __DIR__ . '\autoload.php';
use Facebook\FacebookRedirectLoginHelper;
$helper = new FacebookRedirectLoginHelper( 'http://localhost/app/back.php','APP_ID', 'APP_SECRET' );
echo '<a href="' . $helper->getLoginUrl() . '">Login with Facebook</a>';
?>
</body>
</html>
back.php
<?php session_start(); ?>
<?php
define('FACEBOOK_SDK_V4_SRC_DIR', 'src/Facebook/');
require __DIR__ . '\autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
FacebookSession::setDefaultApplication( 'APP_ID', 'APP_SECRET' );
$helper = new FacebookRedirectLoginHelper( 'http://localhost/app/back.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ( $session ) {
// Logged in.
echo 'logged in';
echo '<hr/>';
// set session from cookie or via helper
$user_id = $session->getSessionInfo()->asArray()['user_id'];
$request = new FacebookRequest(
$session,
'GET',
'/' . $user_id
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
echo 'you are ' . $graphObject->getProperty( 'name' );
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf=8" />
<title>FB App BACK</title>
</head>
<body>
</body>
</html>
登录成功进行,我可以看到我已登录。但是,当重新加载页面时,我得到Undefined variable: session in C:\wamp\www\app\back.php on line 21
,这是行
if ( $session ) {
如何在包含多个页面的网站中保持会话?