我有一个Web应用程序,要求用户使用其google帐户登录。但是,登录后,它不会将我重定向到另一个页面。它停留在登录页面上。
登录前:
登录后:
我尝试使用php Header()函数,但是它没有重定向我,我错过了什么吗?
<?php
ob_start();
session_start();
require_once 'google-api-php-client-2.2.2/vendor/autoload.php';
$conn = new mysqli("localhost","root","","labelimagetool");
if($conn->connect_error){
die("Connection failed: ".$conn->connect_error);
echo 'Unable to connect to db!';
}
else{
echo 'Connected to db!';
}
$redirect_uri = 'http://localhost/labelimagetool/tool.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setDeveloperKey($api_key);
$client->setRedirectUri($redirect_uri);
//$service = new Google_Service_Oauth2($client);
$client->addScope(Google_Service_Oauth2::USERINFO_EMAIL);
$client->setAccessType('offline'); // offline access
$client->setIncludeGrantedScopes(true);
//$client->authenticate(isset($_GET['code']));
//$client->authenticate($code);
$plus = new Google_Service_Plus($client);
if(isset($_REQUEST['logout'])){
session_unset();
}
if(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://'.$_SERVER['HTTP_HOST'].'/tool.php';
header('Location:'.filter_var($redirect,FILTER_SANITIZE_URL));
exit();
}
else{
echo "no value";
}
if(isset($_SESSION['access_token']) && $_SESSION['access_token']){
$client->setAccessToken($_SESSION['access_token']);
$me = $plus->people->get('me');
$email = $me['emails'][0]['value'];
$name = $me['displayName'];
$sqlEmail = "SELECT * FROM users WHERE email='".$email."'";
$checkEmail = mysqli_query($conn,$sqlEmail);
if(mysqli_num_rows($checkEmail) >0){
}
else{
$insertStmt = "INSERT INTO users ('email','name','status') VALUES('".$email."','".$name."','user')";
mysqli_query($conn,$insertStmt);
}
}
else{
$authUrl = $client->createAuthUrl();
}
ob_end_flush();
?>
请帮助我。谢谢。
答案 0 :(得分:2)
您的问题是您正在设置重定向标头,但随后却没有通过。
这部分代码正在执行:
if(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://'.$_server['HTTP_HOST'].'/tool.php';
header('Location:'.filter_var($redirect,FILTER_SANITIZE_URL));
}
但是在设置Location
标头之后,您并没有退出PHP,而是继续:
if(isset($_SESSION['access_token']) && $_SESSION['access_token']){
.....
}
然后最后执行此代码:
else{
$authUrl = $client->createAuthUrl();
}
解决方案:
更改为以下代码块:注意添加了exit()
if(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://'.$_server['HTTP_HOST'].'/tool.php';
header('Location:'.filter_var($redirect,FILTER_SANITIZE_URL));
exit();
}
建议:
如果您打算将HTTP标头发送到客户端,请始终在PHP代码的开头添加ob_start();
。这将打开输出缓冲。这样可以防止在标题之前发送输出。在您的代码退出之前,请跟踪ob_end_flush();
。
<?php
ob_start();
启用错误报告。在您的PHP文件顶部添加(加上我的其他建议):
<?php
// enable output buffering
ob_start();
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
此外,如果您具有PHP错误日志记录设置,您将能够看到错误和警告。我敢打赌,有一些问题需要修复。