目前我有一个问题,设置会话变量。
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: home.php");
}
require 'pdoconnect.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if(count($results) > 0 && password_verify($_POST['password'], $results['password']) ){
$_SESSION['user_id'] = $results['id'];
header("Location: glogin.php");
$_SESSION['email'] = $_POST['email'];
$email = $_SESSION['email'];
} else {
$message = 'Login failed, try again';
}
endif;
上面你可以看到我使用的登录脚本,这段代码运行在
login。
<form action="login.php" method="POST">
<input type="email" placeholder="Enter your e-mail" name="email" required>
<input type="password" placeholder="Enter your password" name="password" required>
<input type="submit" value="Log in">
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
</form>
这是用来登录的表单,表单也运行在
login。
现在问题来了,我想把用户用来登录到一个会话变量的电子邮件,但我不能设置表单动作到另一个页面,因为这样的登录脚本将不再工作。
所以我的问题是:'我如何读取$_SESSION['email']而不改变表单动作?
我已经尝试将login.php包含到另一个页面中,但不幸的是没有工作。
在$_SESSION
赋值之前使用重定向header()
。
:
$_SESSION['user_id'] = $results['id'];
header("Location: glogin.php");
$_SESSION['email'] = $_POST['email'];
$email = $_SESSION['email'];
应:$_SESSION['user_id'] = $results['id'];
$_SESSION['email'] = $_POST['email'];
$email = $_SESSION['email'];
header("Location: glogin.php"); // at last
exit;
如果你想在glogin.php
页中使用$_SESSION['email']
值,那么你必须同时在session_start()
页中启动会话。
最后一个建议,您可以在会话中使用$results
值而不是$_POST
值,就像id
字段一样:
$_SESSION['email'] = $results['email'];
你还需要了解为什么header()
函数之后需要exit()
,你可以阅读这篇文章:PHP: using exit();或死亡();头后("位置:");
使用$_SERVER['PHP_SELF']
代替login.php作为表单操作
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
在使用header('Location: ...')
之后也应该使用exit
。
if (isset($_SESSION['login'])) {
header("Location: index.php");
exit;
}
如果在执行重定向后没有退出,则仍将执行完整的脚本。有些变量可能没有设置好,简而言之……仅exit;
在设置会话变量之前重定向。
$_SESSION['user_id'] = $results['id'];
$_SESSION['email'] = $_POST['email'];
header("Location: glogin.php");
exit;
更新不确定你到底想用gloging.php做什么,但它应该看起来像这样。
<?php
session_start();
if (isset($_SESSION['user_id'])) {
echo $_SESSION['email'];
exit;
} else {
header("Location: nologin.php");
exit;
}
?>