【发布时间】:2013-09-08 15:10:09
【问题描述】:
我在这里的第一篇文章。提前感谢您的任何答案:)
无论如何,我有一个登录脚本 (login.php),在提交凭据时它具有以下代码:
if(isset($_POST['submit'])) {
$password=$_POST['password'];
$email = (string)$_POST['email'];
try {
$db = new PDO('mysql:dbname=dbname;host=localhost', 'username', 'password'); // MY REAL DETAILS ARE USED HERE, JUST DON'T NEED THEM ON THE INTERNET
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sth = $db->prepare('SELECT * FROM members WHERE email = :email LIMIT 1');
$sth->bindParam(':email', $email);
$sth->execute();
$user = $sth->fetch(PDO::FETCH_OBJ);
// Hashing the password with its hash as the salt returns the same hash
if (crypt($password, $user->password) == $user->password) {
if($user->id > 0) {
if($user->status == 'Y' && date('Ymd', time($_SESSION['expiration'])) == date('Ymd')) {
$data = array('status' => 'D');
$update = mysql_update('members', $data, '`id`='.$_SESSION['memberID']);
}
$status = mysql_select('SELECT status FROM members WHERE id='.$user->id);
$_SESSION['memberID'] = $user->id;
$_SESSION['expiration'] = $user->expiration_date;
$_SESSION['timeout'] = time();
if(isset($_REQUEST['url'])) header('Location: '.$_REQUEST['url']);
else header('Location: account.php');
} else {
$error = "Whoops! That wasn't supposed to happen, please contact the webmaster.";
}
} else {
$error = "Sorry, something didn't quite match up. Please try again.";
// print $user->password;
// print "<br />";
// print crypt($password, $user->password);
}
}
问题在于,当设置$_REQUEST['url'] 时,会发生重定向,但会立即发送回我的登录脚本。
示例:我的网址是mysite.com/login.php?url=account.php,我在登录时点击提交。它运行上面的代码,并直接将我发送回login.php,就好像没有设置会话一样。告诉account.php返回登录的代码是这样的:
if(!isset($_SESSION['memberID'])) header('Location: login.php?url=account.php');
我不明白为什么,但是当我硬刷新CTRL + F5 时,会话已设置,它会将我带回index.php,因为login.php 说
if(isset($_SESSION['memberID'])) header('Location: index.php');
我正在拔头发,因为这让我非常困扰。任何帮助表示赞赏。
如果你们好奇,我正在使用 PHP 版本 5.3.26。我知道我的会话何时设置,因为我有一个页面 (php.php) 可以打印出我与 var_dump($_SESSION); 的会话
谢谢!
编辑:我的问题不是重定向。从逻辑上讲,这是应该发生的事情,按顺序:
- 用户输入登录数据并点击提交
- 然后登录页面会检查他们的数据
- 设置会话变量
- 转到account.php
Account.php 应该查看我的会话是否设置if(!isset($_SESSION['memberID'])) header('Location: login.php?url=account.php');
所以这一行是没有阅读我的会话的部分。
回到 login.php 设置会话:
$_SESSION['memberID'] = $user->id;
$_SESSION['expiration'] = $user->expiration_date;
$_SESSION['timeout'] = time();
if(isset($_REQUEST['url'])) header('Location: '.$_REQUEST['url']);
else header('Location: account.php');
这部分必须正常工作,因为正在设置会话并转到 account.php,但是 account.php 在设置时没有读取会话。为什么?
这也不是缓存问题,因为我已清除缓存并尝试限制对页面的缓存。
【问题讨论】:
-
你会在脚本中的所有内容之前调用 session_start() 吗?
-
我一定遗漏了一些东西,因为当您仅在 $_POST 发生的情况下检查它时,您如何获得 $_REQUEST['url'] ?您是否将其设置在您未提供的代码中?
-
@Roberto - 是 session_start() 在每一页上。
-
@Tim - mysite.com/login.php?url=account.php
-
是的,但您正在 $_POST 内部寻找它。请参阅我的答案以获得澄清。