這是我第一次在 PHP 中使用會話,似乎我在做一些邏輯錯誤的事情。我正在撰寫一個忘記密碼頁面,用戶在其中向表單輸入一個隨機生成的代碼,并在點擊提交后顯示一條訊息,無論代碼是否正確。如果是這種情況,用戶會嘗試 3 次輸入正確的代碼,否則將被重定向到重置密碼頁面,否則他將被重定向到登錄頁面。我正在使用一個變數$_SESSION['attempts'],它在上一頁中設定為 3,并使用$_SESSION['code']變數來存盤也從上一頁隨機生成的代碼。
錯誤資訊正確顯示,即當用戶輸入錯誤代碼時,彈出警告對話框并說他還有 2,1 或 0 次嘗試,即使用戶輸入正確的代碼,他也被重定向到重置密碼頁面。但是在達到 0 次嘗試后,重定向不起作用。知道如何解決這個問題嗎?提前致謝。
這是下面的PHP代碼:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
// input code of the user once it is submitted
$_code = filter_input(INPUT_POST, 'code');
if($_SESSION['attempts'] != 0){
// check if code != the generated code
if($_code != $_SESSION['code']){
$_SESSION['attempts']--;
echo "<script type='text/javascript'>alert('ERROR : Wrong code entered. You have {$_SESSION['attempts']} attempts left.');</script>";
//success - redirect to reset password page
} else {
//header to reset password page
}
}
}
// if attempts === 0 -> redirect to login page (THIS PART DOESNT WORK)
if (($_SESSION['attempts']=== 0 || $_SESSION['attempts'] === '0')) {
//header to login page
}
?>
uj5u.com熱心網友回復:
您已將“ attemp == 0 ”條件排除在 Post 請求之外。將其移動到 Post 請求的內部。那么你的代碼應該如下所示:
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$_code = filter_input(INPUT_POST, 'code');
if($_SESSION['attempts'] != 0){
if($_code != $_SESSION['code']){
$_SESSION['attempts']--;
echo "<script type='text/javascript'>alert('ERROR : Wrong code entered. You have {$_SESSION['attempts']} attempts left.');</script>";
} else {
//header to reset password page
}
}
else {
echo "Now, I need to go login page";
}
}
?>
uj5u.com熱心網友回復:
親愛的 只需在會話開始后進行一次檢查,為了測驗此腳本,還可以輸入一些 $_SESSION['code'] 值,或者如果您已經有了,則可以繼續執行以下邏輯。請記住將此檢查放在您定義嘗試的索引或第一頁上。我還更新了您的 js 腳本并包含了 location.href,以便您可以在重定向之前看到警報。
<?php
session_start();
if(!isset($_SESSION['attempts']))
{
$_SESSION['attempts']=3;
}
if ($_SERVER["REQUEST_METHOD"] == "POST"){
// input code of the user once it is submitted
$_code = filter_input(INPUT_POST, 'code');
if($_SESSION['attempts'] != 0){
// check if code != the generated code
if($_code != $_SESSION['code']){
$_SESSION['attempts']--;
echo "<script type='text/javascript'>alert('ERROR : Wrong code entered. You have {$_SESSION['attempts']} attempts left.');location.href='index.php';</script>";
//success - redirect to reset password page
} else {
//header to reset password page
}
}
}
// if attempts === 0 -> redirect to login page (THIS PART DOESNT WORK)
if (($_SESSION['attempts']=== 0 || $_SESSION['attempts'] === '0')) {
//header to login page
}
?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396702.html
