我有以下代碼,當用戶登錄時,它們會顯示兩個文本框和一個複選框。PHP會話,COOKIES和記住我功能
設置3個曲奇,username
,password
和remember
所有工作,並在日誌中腳本本身是comepletely罰款(我明白,在cookie中存儲散列密碼是不是最好的做法,但現在它會做)。
雖然會發生什麼,但用戶重新訪問login.php
頁面(這一個),而他們已經登錄在cookie中,因爲$ _POST條件沒有被滿足而被一個一個地刪除,因此行下面正在執行。我怎樣才能防止這種情況發生。此外,任何建議來清理代碼,我將無疑會結束了很多重複代碼將不勝感激。由於
snippet from the 'login.php' page below
} elseif (!$_POST['remember']) {
$past = time() - 100;
if (isset($_COOKIE['remember'])) {
setcookie('remember', '', $past);
} elseif (isset($_COOKIE['username'])) {
setcookie('username', '', $past);
} elseif (isset($_COOKIE['password'])) {
setcookie('password', '', $past);
}
}
login.php
<?php
session_start();
include("includes/config.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
$odb = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$username = "";
$password = "";
if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$username = $_COOKIE['username'];
$password = $_COOKIE['password'];
} elseif (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$password = md5(DB_SALT.$password);
}
$sql = "SELECT * from tblMembers WHERE username = :username";
$query = $odb->prepare($sql);
$query->execute(array(":username" => $username));
$results = $query->fetchAll();
if($results !== FALSE && $query->rowCount()>0) {
if($results[0]['passwordHash'] == $password) {
$_SESSION['username'] = $username;
$_SESSION['userID'] = $results[0]['userID'];
if($_POST['remember']) {
$month = time() + (60 * 60 * 24 * 30);
setcookie('remember', $_POST['username'], $month);
setcookie('username', $_POST['username'], $month);
setcookie('password', $results[0]['passwordHash'], $month);
} elseif (!$_POST['remember']) {
$past = time() - 100;
if (isset($_COOKIE['remember'])) {
setcookie('remember', '', $past);
} elseif (isset($_COOKIE['username'])) {
setcookie('username', '', $past);
} elseif (isset($_COOKIE['password'])) {
setcookie('password', '', $past);
}
}
header("Location: "."index.php");
} else {
echo "password incorrect";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Username:
<?php
if(isset($_COOKIE['username'])) {
echo "<input type=\"text\" id=\"username\" name=\"username\" maxlength=\"40\" value=".$_COOKIE['username'].">";
} else {
echo "<input type=\"text\" id=\"username\" name=\"username\" maxlength=\"40\" value=\"\">";
}
?>
Password: <input type="password" id="password" name="password" maxlength="50">
Remember Me:
<?php
if(isset($_COOKIE['remember'])) {
echo "<input type=\"checkbox\" id=\"remember\" name=\"remember\" checked=\"checked\">";
} else {
echo "<input type=\"checkbox\" id=\"remember\" name=\"remember\">";
}
?>
<input type="submit" id="submit" name="submit" value="Log In">
</form>
</body>
</html>
這個cookie問題如何與mysql和PDO相關? – 2013-02-26 13:16:01
因爲它包含MySQL和PDO代碼,所有其他類都與此有關,所以我猜想,如果我接觸到更多的人,那麼我將得到一個更加定製的答案,涉及我希望實現的內容。 – Mike 2013-02-26 13:27:55