faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

21 of 32 people (66%) answered Yes
Recently 5 of 10 people (50%) answered Yes


After a form is submitted and a script is run, how do I keep the script from running again if the user clicks 'refresh' in the browser?

Nov 27th, 2006 22:16
jean korte, Michael Stack,

The best way to do this is to use session variables.  At the very start
of your script, before ANY output  you need to start the session with
or if you are starting with html file you can put it at the very top, before
the <html> statement:
<?php session_start(); ?>
You will get an error and it will not work unless you open the session
at the very beginning.
Now you need a session variable that you will set when your script is
done.  Then the very first thing that your script does is to check if
this variable is set and if it is, it gives an appropriate message and
exits.  This must be a session variable so that the value is retained
when the user reloads the page.
Lets say, when your script is finished, you set a session variable like
Let's further assume that this variable is only set when you are
finished and is otherwise undefined.
At the top of your script you do something like the following:
echo "Processing is complete, page cannot be re-loaded";
This variable is stored in the session cookie on the server.  The
session cookie expires when the browser is closed.  (This is not the
same as the PHPSSID cookie that is stored on the client.)
I use this with my contact form to prevent the user from sending a
duplicate message.  The only way they can send another message is to
close the browser and re-open it. 
Hope that this helps.