4

I have 2 pages :

page1.php :
- has a form with text box and a "submit" button. Eg : <form name="frm_register" action="page1.php" method="post">

- php and mysql code to store the value of textbox to database. Javascript will redirect the page to php2.php after the value is submitted to database. Eg :

$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query, $connection);
echo '<script language="javascript">window.location="page2.php";</script>';

page2.php
- mysql retrieve the data from database and display on this page.

Problem : When I press "back" button, the browser will pop up a warning message saying that the form will be resubmit. How to prevent resubmit the form when click "back" button? Is it I need to clear the cache of page1.php? How to do it with php or javascript or ajax?


Update 1 : Thanks for the answer of replacing javascript window.location="page2.php" to php header('Location: home2.php');. It fix 80% of problem. The rest of 20% problem show below :
    if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
                if (($username != "") AND ($username != $_SESSION[username])){
                    $_SESSION['servertime'] = $servertime; 
                    $_SESSION['username'] = $username;
                    $query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
                    $result = mysql_query($query20, $connection);
                    header('Location: page2.php');
                    exit;
                } else {
                    echo "same name"; //problem here
                }
            }else{
                echo "submit multiple data too fast"; //problem here too.
            }
   }

The problem happen when do the following steps :
1) User submit data successfully, jump to page2.php view records.
2) User click "back" button, jump back to page1.php.
3) User submit data fail, stay on page1.php. (because too fast or same name)
4) User submit data successful, jump to page2.php view records.
5) User click "back" button, but browser shows warning message "form will be resubmited".

The problem is because of Step 3. Step 3 didn't run header('Location: page2.php');, didn't jump to page2.php. So it cause Step 5 show the warning message. How to fix this problem?


Update 2 : I have figured out the solution to fix the 20% problem, it works perfectly. I use session['error123'] to decide whether or not want to display the error message "same name". I kill session['error123'] if success submit data to database or if success jump to page2.php. I also use header('Location: page1.php'); to redirect to own page (same page) to make the page forget about form submission previously. Example of codes :
if ($_SESSION['error123'] == "toofast"){
    echo $_SESSION['error123'] ;
}elseif ($_SESSION['error123'] == "samename"){
    echo $_SESSION['error123'] ;
}

if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
                if (($username != "") AND ($username != $_SESSION['username'])){
                    $_SESSION['username'] = $username;
                    $query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
                    $result = mysql_query($query20, $connection);
                    $_SESSION['error123'] = "aa";
                    header('Location: http://localhost/plekz/page2.php');
                    exit;
                } else {
                    $_SESSION['error123'] = "samename";
                    header('Location: http://localhost/plekz/page1.php');
                    exit;
                }
            }else{
                $_SESSION['error123'] = "toofast";
                header('Location: http://localhost/plekz/page1.php');
                    exit;
            }
        }
    }

Note : You need to buffer the output by <?php ob_start();?> because $_SESSION cannot put before header(). Buffer will stop all output including session, let header() send the output first.

zac1987
  • 2,721
  • 9
  • 45
  • 61
  • The 20% left in your question are the same as [I am confused about PHP Post/Redirect/Get](http://stackoverflow.com/questions/7681755/i-am-confused-about-php-post-redirect-get), see as well this [tutorial](http://kyleschaeffer.com/best-practices/10-things-a-website-should-never-ever-do/), section *2. Never allow form resubmissions*. – hakre Oct 13 '11 at 07:55
  • @hakre, the solution that u suggested is separate the script that submits the form data, and the script that receives and processes that data right? If I do so, my page1.php must responsible on two tasks : 1) show the form with textbox and submit button on the page if $_Get['success']!=true, and must show all the records if $_Get['success']==true. If display records must depend of php if else statement, then I need to wrap the html codes of displaying records by php echo. It will be a lot of works to wrap all html in php echo... omg. – zac1987 Oct 13 '11 at 08:54

6 Answers6

4

Rather than

echo '<script language="javascript">window.location="page2.php";</script>';

you should use the header() function to redirect your user after the submission.

So in psuedo code,

click submit on page.php action page1.php page1.php submits data to database calls

header('Location: http://example.com/page2.php');

This should prevent your clicking back problem

hakre
  • 193,403
  • 52
  • 435
  • 836
Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108
  • Hello, ur solution fix 80% of problems, I did update my question to show u the rest of 20% problem, please teach me how to fix it. Thank you. – zac1987 Oct 13 '11 at 03:36
  • @BenSwinburne: Any HTTP header requires one space (SP) after the colon. Location Header requires absolute URI. Take care. – hakre Oct 13 '11 at 07:50
  • @hakre MY example uses an absolute URI... scheme, hostname and abs path are there as well as a single space. What were you intending with your comment? – Ben Swinburne Oct 13 '11 at 08:12
  • @BenSwinburne: Just wanted to let you know that I *edited* your answer (fixed it) so you know about it. That's all ;) – hakre Oct 13 '11 at 08:19
  • @hakre ahhh I see! What did I have before. I was looking at it after your comment thinking eh?! that's right...! Thanks – Ben Swinburne Oct 13 '11 at 08:29
  • @hakre: I did test the code with header("page2.php"), it works too. So the code can actually work without "location" and without full path, the code is not sensitive. – zac1987 Oct 13 '11 at 08:32
  • 1
    @zac1987: Only that it works for you must not mean it works for *every* browser. Because this is not trivial, there is a standard where all those headers are defined and where it's written down how things should be used. It's often called RFC, for example you're using HTTP 1/1 Location: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30 – hakre Oct 13 '11 at 08:37
1

You can prevent the re-submission by implementing the Post-Redirect-Get (PRG Pattern).

Could be just a one-line if you've got the http_redirect function:

http_redirect("page2.php");

Instead of your javascript echo.

If not, that are two lines:

header("Location: http://example.com/page2.php");
exit;

Replace example.com with site's your hostname.

Related: Back button re-submit form data ($_POST); I am confused about PHP Post/Redirect/Get

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Hello, ur solution fix 80% of problems, I did update my question to show u the rest of 20% problem, please teach me how to fix it. Thank you. – zac1987 Oct 13 '11 at 03:36
  • Thank you. Already found the two different solutions. thanks for your suggestion :) – zac1987 Oct 13 '11 at 09:11
0

Add this code in the page that is showing as offline when the user clicks the back button:

<?php
 session_start();
 header_remove("Expires");
 header_remove("Cache-Control");
 header_remove("Pragma");
 header_remove("Last-Modified");
?>
Kirk Backus
  • 4,776
  • 4
  • 32
  • 52
0

One way is to submit the Formdata via Ajax to a remote Script and if the Query returns success you can jump the a "Thank You" Page. So the User can hit the Back Button and the "Reload" Request doesn't pop up.

Hope the Idea helps you

Jan Wiemers
  • 341
  • 1
  • 6
  • after click "back" button, the page1.php will run the ajax code again without clicking "submit" button, because page1.php has the cache...so I think ajax also can't fix the problem... – zac1987 Oct 12 '11 at 23:10
0

Can you do it via an Ajax call instead? No action on the form, and the submit will call a the Ajax function. The Ajax call will execute the query, and provide a response (you can just echo a result), and you can then provide dynamic feedback based on the result. You'd never leave the page.

<form id="thisForm">
...form input fields...
<input type="button" onclick="return submitForm('thisForm')"/>
</form>

function submitForm(formId) {
    $.ajax( {
        type: "post",
        url: 'page2.php',
        data: $('#' + formId + ' input').serialize(),
        ... any other Ajax parameters...,
        success: function(data) {
        }
    });
    return false;
}
Keith DC
  • 661
  • 1
  • 9
  • 24
  • And btw, when an Ajax call is made, you never leave the page (e.g., page1.php), so the back button would simply take you to where you were prior to page1.php. A page refresh also would not execute the Ajax call again. – Keith DC Oct 12 '11 at 23:14
  • From your code, u suggest me don't leave the page1.php page, but I need to show the records / datas on page2.php, which mean I need to leave page1.php and go to page2.php. This is not a registration system, so please don't misunderstand about it. After the user submit the data on page1.php, the user MUST redirect to page2.php. Any other solution? – zac1987 Oct 12 '11 at 23:24
  • I see the onlick function already!! If refresh the page, the function will not recall again until the button is clicked again. Thank you very much! I think your answer will fix my problem. I am going to test it now. Thanks. – zac1987 Oct 12 '11 at 23:27
  • You can return the data back from page2 to the Ajax call (from page2 after it's done what it needs to do), then present the data dynamically while you're still on page1. If you return a table's worth of data, you can then use jQuery to put that information into an empty DIV that's on page1. – Keith DC Oct 12 '11 at 23:28
  • There's a lot that goes into Ajax. If you want to use a library such as jQuery, you can look into: http://api.jquery.com/jQuery.post/ – Keith DC Oct 12 '11 at 23:30
-1

Create a Session like shown here

You should use session and validate the user from every page and you will amaze how SESSION works! AMAZING!

αƞjiβ
  • 3,056
  • 14
  • 58
  • 95
Jordan
  • 1