weixin_33696822 2016-12-02 12:02 采纳率: 0%
浏览 30

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.

  • 写回答

3条回答 默认 最新

  • weixin_33744854 2016-12-02 12:13
    关注

    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)

    评论

报告相同问题?