I would like to prevent the session to increment if the page gets refreshed.
I tried to check if POST was already set, like this if (isset($_POST)){$_SESSION['page']++;}
, but it didn't solve the problem, because the form has to be sent more than once.
I would like $_SESSION['page']++ to increment only when I submit data from the form, not when the page gets refreshed.
EDIT: I posted the whole code as it wasn't clear how it works.
IMPORTANT: Apparently, the POST/REDIRECT/GET method won't work, as I don't need to redirect the user to another page after the data gets sent. Instead I need to reload the same page. Don't take my word for granted.
//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> ```