[英]PHP:my session_variables shows when the page refresh
我知道這是一件很簡單的事情,但我不知道。 我在同一頁上有一個注冊表單的php代碼,其中任何條件與代碼匹配時都會顯示一些會話變量。
代碼結構如下:
<?php
session_start();
if(isset($_POST['signup'])
{
if(condition)
{
$_SESSION['err1']="string";
}
else
{
$_SESSION['err2']="string";
}
}
?>
//HTML form
<?php if(isset($_SESSION['err1']) {?>
<li><?php echo $_SESSION['err1'];}?></li>
<?php if(isset($_SESSION['err2']) {?>
<li><?php echo $_SESSION['err2'];}?></li>
//rest of the form
我的代碼中有更多if-else塊。 最初,當條件匹配時,將顯示會話消息。 但是,只要頁面刷新,就會顯示另一個會話消息以及上一個會話消息。
這是使用表單編碼的正確方法嗎? 因為我想在HTML表單中顯示錯誤消息。
回顯后,只需取消設置會話變量即可。
<li><?php echo $_SESSION['err1'];} unset($_SESSION['err1']); ?></li>
那可能是因為您沒有清空會話變量。
在2個HTTP請求之間,會話保留在服務器上(僅在每個請求時重新加載)。
因此,如果您在第一次調用時在$_SESSION['error1']
上放置一條消息,它將顯示該消息。 然后,在第二負載,如果你是把消息放在$_SESSION['error2']
你將也有消息error1
因為會話保持你的數據。
顯示表格后,您應該清空所有會話消息
這是一個使用會話回顯錯誤的錯誤示例。
我在php開始時做了很多次。
$errors = array(); // make a empty array errors before the conditional statements
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Submit'])) {
//handle your POST variable
if(condition1){
$errors[] = "some error";
}
if(condition2) {
$errors[] = "some another error";
}
//more conditions
if (!empty($errors)) {
//process your form data if there is no errro
} else {
//display back your form along with Errors
if(isset($errors) && !empty($errors)) {
foreach($errors as $error) {
echo "<p class = 'error'>" . $error . "</p>";
}
}
<form action = "" method = "POST">
//your form elements
</form>
}
}
在php頁面的第一行中,您可以編寫if條件,可以嘗試三行中的任何一行
if(isset($_SESSION))
{
unset($_SESSION);
unregister($_SESSION['variable-name']) // try this also
session_destroy(); //try this also
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.