这里可能有一些明显的东西,但我真的无法弄清楚为什么这个setcookie调用不起作用。在我的PHP安装上启用了Cookie,在设置Cookie之前我没有发送任何数据,并且当我尝试使用ob_start()
和ob_end_flush()
时,我的代码完全没有区别。
仅供参考,db.php文件仅包含使用PDO连接到数据库的脚本。什么都没有输出,我不明白为什么会有任何不同。
<?
session_start();
if (!$_POST['username'] || !$_POST['password']) {
echo "Invalid username or password!";
exit();
}
require('../inc/db.php');
try {
$stmt = $db->prepare("SELECT id, username FROM users WHERE username = ? AND password = ? LIMIT 1;");
$stmt->execute(Array($_POST['username'], md5($_POST['password'])));
$rows = $stmt->fetchAll();
} catch (PDOException $ex) {
echo "Database query error!";
exit();
}
if (count($rows) == 1) {
$_SESSION['username'] = $rows[0]['username'];
$_SESSION['userid'] = $rows[0]['id'];
if ($_POST['remember-me'] == "on") {
$token = substr(base64_encode(mt_rand()), 0, 20);
try {
$stmt = $db->prepare("UPDATE users SET token = ? WHERE id = ?;");
$stmt->execute(Array($token, $_SESSION['userid']));
setcookie("login", $_SESSION['userid'] . "/" . $token, time()+3600*24*365);
echo "success";
} catch (PDOException $ex) {
echo "Database query error!";
exit();
}
} else {
echo "success";
}
} else {
echo "Invalid username or password!";
}
?>
编辑:以下是响应标头,您可以看到没有Set-Cookie标头...
Pragma: no-cache
Date: Thu, 07 Aug 2014 23:25:06 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Content-Type: text/html
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: close
Content-Length: 7
Expires: Thu, 19 Nov 1981 08:52:00 GMT