How to Tell If a Form Has Been Submitted Using PHP

Consider this scenario:

You have a form which submits to itself (e.g. a simple contact form). The first time it loads you don’t want to do anything other that render the form.

However, when a user hits Submit, you want to process whatever data you have received, then re-render the form, including (for example) error messages where appropriate.

Until recently, I was doing it like this:

<?php
  if (isset($_POST['submitted'])){
    // The form has been submitted
    // We can do stuff here
  }
?>

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

I was using a hidden input field which, when the page first rendered would be not be set, yet after the form had been submitted would have a value of 1.

Then it was pointed out to me that this is a bit clunky and can be done much more elegantly:

<?php
  if ($_SERVER['REQUEST_METHOD'] == "POST"){
    // The form has been submitted
    // We can do stuff here
  }
?>

You don’t need the hidden field at all. When the form first renders:

$_SERVER['REQUEST_METHOD'] == "GET"

When the form is submitted:

$_SERVER['REQUEST_METHOD'] == "POST"</pre>

Simples!


This post currently has 4 responses

  1. Graham says:

    Why not just check $_POST[‘submit’] ?

    • hibbard.eu says:

      Good point.

      The only thing that speaks against it is that you need to give your submit <input> a name or it won’t be available using $_POST[‘submit’]:

      <input type="submit" value="Submit" name="submit" />

      whereas with the above method even this will work:

      <button>Submit</submit>

  2. john says:

    Try this! This technique is the most recommended since it seems to be recognized as a “great practice” by the “Coding Academy”

    Add Task: //Check if the form is submitted
    if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['newtaskname'])){
    
  3. Ryan Bayne says:

    All true. However if your working in a CMS like WordPress you may need to be checking for submissions from a specific software such as your own plugin and avoiding other submissions. That is where a hidden input works just fine. There is a but…

    I wanted to mention something that many developers totally miss.

    Like any source, the hidden input can be edited. We should not trust simply because the input exists and we should not trust the value of a hidden input. I have a solution in my #Wordpress plugins for this, see CSV 2 POST the latest.

    What is key for students to know is that all of the methods on this page suit different scenarios better. There is no general right or wrong and that is often the case in development.

Comments are closed!