【发布时间】:2020-06-14 12:58:19
【问题描述】:
如果页面被刷新,我想阻止会话增加。
我试图检查 POST 是否已经设置,例如 if (isset($_POST)){$_SESSION['page']++;},但它没有解决问题,因为表单必须发送多次。
我希望 $_SESSION['page']++ 仅在我从表单提交数据时递增,而不是在页面刷新时递增。
编辑:我发布了整个代码,因为不清楚它是如何工作的。
重要提示:显然,POST/REDIRECT/GET 方法不起作用,因为我不需要在发送数据后将用户重定向到另一个页面。相反,我需要重新加载同一页面。不要认为我的话是理所当然的。
//Start using session-variables.
session_start();
//Game is started.
if (!isset($_SESSION['page']))
{
$_SESSION['page']=1;
}
else
{
//Game is on, read answer from previous page.
$answer=$_POST['answer'];
}
//Figure out what to display.
switch ($_SESSION['page'])
{
case 1: //First page of the game.
$picture="pictures/perch.gif";
$option1="Perch-pike";
$option2="Pike";
$option3="Perch";
$option4="Ruffe";
break;
case 2: //Second page of the game.
$picture="pictures/brownhare.gif";
$option1="Brown hare";
$option2="Wolverine";
$option3="Arctic hare";
$option4="Badger";
$_SESSION['answer1']=$answer;
break;
case 3: //Third page of the game.
$picture="pictures/moose.gif";
$option1="Reindeer";
$option2="Fallow deer";
$option3="Roe deer";
$option4="Moose";
$_SESSION['answer2']=$answer;
break;
case 4: //On last page answers are evaluated.
$points=0;
$answer3=$_POST['answer'];
if ($_SESSION['answer1']==3)
{
$points++;
}
if ($_SESSION['answer2']==1)
{
$points++;
}
if ($answer3==4)
{
$points++;
}
print "
<h2>Your score is $points</h2>";
print "
<a href='quiz.php'>New game</a>
<br>";
print "
<a href='../index.htm'>Back to examples</a>
<br>";
session_destroy();
exit;
}
$_SESSION['page']++;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Huntersman's examination game</title>
</head>
<body>
<form method="post" action="quiz.php">
<center>
<h2>What is this?</h2>
<table border=1>
<tr>
<td width="300">
<img src="
<?= $picture?>">
</td>
<td>
<table>
<tr>
<td>
<?= $option1?>
</td>
<td>
<input type="radio" name="answer" value="1" checked>
</td>
</tr>
<tr>
<td>
<?= $option2?>
</td>
<td>
<input type="radio" name="answer" value="2">
</td>
</tr>
<tr>
<td>
<?= $option3?>
</td>
<td>
<input type="radio" name="answer" value="3">
</td>
</tr>
<tr>
<td>
<?= $option4?>
</td>
<td>
<input type="radio" name="answer" value="4">
</td>
</tr>
<tr>
<td>
</table>
</td>
</tr>
</table>
<br>
<input type="submit" value="Answer">
</center>
</form>
</body>
</html> ```
【问题讨论】:
-
为什么不在表单中添加页码。
-
使用这个:
if (!empty($_POST)){$_SESSION['page']++;}检查表单是否已提交! -
@SerhiiPuchkovskyi 当用户按 F5 时,它将重新提交表单并且条件不会按预期运行。
-
@DhavalPurohit 你的意思是“行动”?我必须在同一页面上至少增加 5 次会话。不确定这是否能回答您的问题。
标签: php forms session input refresh