Checking if form has been submitted - PHP

Anonymous picture Anonymous · Oct 10, 2011 · Viewed 300.5k times · Source

What is the best way of checking whether or not a form has been submitted to determine whether I should pass the form's variables to my validation class?

First I thought maybe:

isset($_POST)

But that will always return true as a superglobal is defined everywhere. I don't want to have to iterate through each element of my form with:

if(isset($_POST['element1']) || isset($_POST['element2']) || isset(...etc

Whilst writing this question I thought of a much more basic solution, add a hidden field to act as a flag that I can check.

Is there a 'cleaner' way to do it than adding my own flag?

Answer

matino picture matino · Oct 10, 2011

For general check if there was a POST action use:

if (!empty($_POST))

EDIT: As stated in the comments, this method won't work for in some cases (e.g. with check boxes and button without a name). You really should use:

if ($_SERVER['REQUEST_METHOD'] == 'POST')