PDA

Click to See Complete Forum and Search --> : [PHP] Checking if a form has been submitted, the correct way...


I_Love_My_Vans
Mar 23rd, 2009, 07:25 AM
Checking that a form has been submitted is one of the first things you will encounter when handling form inputs. For arguements sake, here is my example form:

<form action="script.php" method="post">
<input name="email" type="text" />
<input name="submit" type="submit" value="Submit">
</form>


What the form above will do is post the variables email and submit to the action, script.php.

At this stage most people tend to check to see if a form has been executed by verifying if the submit button variable has been delivered to the receiving script, using code similar to this:

if(isset($_POST['submit']))

In most cases this will work, but there are a few occasions when it won't. To identify when this condition will fail we have to look at the different ways of submitting a form.

There are two ways of submitting a form, one is to click the submit button, the other is to hit return, of which will envoke the submit button. The problem occurs when you hit the return button (as most people do), when using Internet Explorer (the most commonly used browser) and when the submit button does not have focus. This will submit the form, but it will not send the submit variable, which would mean the script we are using above will fail.

Despite this flaw, there is an easy solution:

<input type='hidden' name='submit' />

Here we are setting a hidden variable within our form, so no matter how the form is submitted, the submit variable will always be posted, this means there is no requirement to modify how your PHP works.


I hope this helps,
ILMV


TODO:
- Create demonstration script

kows
Mar 25th, 2009, 07:18 AM
not to step on your toes, but I believe (and please, correct me if I'm wrong) that a better way of checking whether or not a form has been submitted is to check the request method.
if($_SERVER['REQUEST_METHOD'] == "POST")

I_Love_My_Vans
Mar 27th, 2009, 09:00 AM
Blast :), never realised that one existed.

It still demonstrates that my initial method is the incorrect way of checking if a form has been submitted, changing it to the way you suggest would fix this problem.

Many thanks Kows!

yogiyang
Apr 24th, 2009, 08:44 AM
Thanks both of you for such a simple solution.

Tobiasgar
Aug 31st, 2011, 05:06 AM
agree)) simple and quick solution..good job guys!! personally i've never done it on my own:thumb: