PHP页面刷新问题

I am working on an Online Quiz.
On every click of the 'next question' button, I have tried the following:

if(isset($_POST['submit']) && isset($_POST['ans']))
{
  //process answers and fetch next question
  //Increment the Session variable which contains serial of next question
  $_SESSION['qnum'] = $_SESSION['qnum']+1;
}

Whenever I click on the F5 button, the session gets updated and a new question is fetched.
The session should be incremented only when the next question button is clicked, otherwise it should not be increment.
The following is what I have tried after referring to an article:

$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageWasRefreshed) 
{
  //refetch the current question.
}
else
{
 //refetch the current question and increment the Session Variable 
}
  • This approach worked fine in Mozilla Firefox
  • In IE, both the button click and F5 hits are taken as not refreshed
  • In Chrome, both the button click and F5 are taken as refreshed

I have tried some other variations from other articles on StackOverflow and Google, but those didn't work at all including an ajax based solution.

You should never display a page that was requested with POST.

What you do, is process the POST data, then refresh the page with php.

Like this:

<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
  //handle the POST data
  ...

  // now refresh
  header('location: index.php');  // or what ever url you were on
  exit();
}
// else: show the page
echo '<html> ...';
?>

Notice: if you use header('location: ...') NOTHING must be printed/echoed, not even a space / new line / ...

So the first character of your .php file must be "<" (of the of the opening php tags)

May not be the perfect solution but will work

if(isset($_POST['submit']) && isset($_POST['ans']))
{
  //I am assuming we have question id or any  uniq data about question
  if($_SESSION['last_que'] != $_POST['que_id']){
      $_SESSION['qnum'] = $_SESSION['qnum']+1;
      $_SESSION['last_que'] = $_POST['que_id'];
  }

}

If you want to prevent counting all the pages just use arrays and array_search

Following should be your best solution:

$RSig = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));

    if(isset($_SESSION['LastRequest']) && $_SESSION['LastRequest'] == $RSig)
    {
        $_SESSION['reqstat']='refresh';
    }
    else
    {
        $_SESSION['qnum'] = $_SESSION['qnum']+1;
        $_SESSION['reqstat']='newrequest';
        $_SESSION['LastRequest'] = $RSig;
    }

You can use the Session: reqstat to check do thing that is supposed to be done on button click and not on refresh.