Checking if a form was sent via POST method

Since I started programming with PHP I’ve used several ways to check if a form was sent via the POST method. This is useful when the same method of control (or the same script, if you’re using structured programming or not using the MVC model) handle the form presentation and also its submission.

I used three ways, in chronological order, to do this:

1. Hidden field

In this case a hidden input is used as the key verification.

<?php
$post = !empty($_POST['post']);
if ($post) {
  // Form related action...
}
?>
<form action="..." method="post">
  [...]
  <input type="hidden" name="post" value="1" />
  [...]
</form>

2. Attribute passed through the submission button

This is a variation of the first method using the attributes of the submit button of the form instead of a hidden field.

<?php
$post = !empty($_POST['post']);
if ($post) {
  // Form related action...
}
?>
<form action="..." method="post">
  [...]
  <button type="submit" name="post" value="1">Send!</button>
  [...]
</form>

3. Check the request method

This is, in my opinion, the correct way to validate the form submission and I have used on my projects.

<?php
if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
  // Form related action...
}
?>

The last option in addition to being simpler, because it doesn’t require any additional information from the form itself, is more secure because it uses data from the server.

And from this condition, you can create a very simple useful function to use in your PHP projects.

/*
 * Checks if the current request was sent with the HTTP POST method.
 *
 * @return boolean true if the method was sent via POST. false otherwise.
 */
function isPost() {
  return strtoupper($_SERVER['REQUEST_METHOD']) == 'POST';
}

Useful links related to this subject:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s