Checking for Form Submissions in PHP

November 9, 2008

One important topic in PHP is how to know when to handle a form’s submission. If you have two pages–page.html and handle_page.php–the assumption is that whenever handle_page.php is accessed, it’s handling a form. This may not always be true, but is a reasonable enough assumption. However, more commonly the same page is used to both display and handle an HTML form. In such situations, that page is being accessed twice: once when the form is loaded and a second time when the form is submitted back to this same form. The trick is being able to identify which stage the page is in.

An old way to do this is to just check for the presence of the submit variable. Say you define your form’s submit button like so:

<input type="submit" name="submit" value="Go!" />

When the form is submitted, then $_POST[‘submit’] will be set (assuming you use the POST method, of course). Unfortunately this approach will not work in two situations:

  1. If the user submits the form by pressing Enter/Return in Internet Explorer, the $_POST[‘submit’] will not be set.
  2. If you want to use an image for the submit button.

For that matter, you can’t accurately check for the presence of any other form element because the user may not properly fill out the form (something that your PHP script would need to validate).

One reliable solution, which I have been using in my code and books, is to create a hidden input, with any name and any value:

<input type="hidden" name="submitted" value="1" />

Then, when the form is submitted, $_POST[‘submitted’] will be set (assuming, again, that you used the POST method). Worst case scenario, if the user manipulated the form so that it didn’t contain this element, then submitted the form, that form wouldn’t be processed (which it’s best that it isn’t anyway).

Another option, which I’ll likely start using in my books (I’ll have to confirm that there’s no downside), is to check how the page was requested. As you probably know, there are two common methods for requesting a page: GET and POST. These are also the values used for the action attribute of a form. Most pages loaded in the Web browser–by typing in an address or clicking a link–are requested using GET. So the first time a page that both displays and handles a form is accessed (i.e., when the form is displayed), it’s a GET request. When that form is submitted, it’s a POST request (assuming the POST method is used, right? Right). So to check which state the page is in, refer to $_SERVER[‘REQUEST_METHOD’]:

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form... ?>

As I said, this sounds like a good solution to me but I still want to do a little research to confirm that it’s reliable (e.g., that all Web servers on all OSes populate this variable).