How to test which HTML form button was pressed in PHP

execImagine you have a HTML form with several values and two buttons at the bottom. One could say “Do This” and the other “Do That”. How do you know which one was pressed by the user?

It’s fairly easy – but I keep forgetting this time and time again. We do this by accessing the name attribute of the HTML button in PHP.

Consider this HTML form:

<form>
<input type="submit" name="button1" class="button-primary" value="Do This" />
<input type="submit" name="button2" class="button-secondary" value="or Do That" />
</form>

The button classes are WordPress standard “blue” and “grey” button layouts, and the value is what’s written on the button. The secret sauce however is in the name fields here.

Back in PHP when the form is submitted we can access the $_POST variable which an array of values we’re getting back from the form. We can access them like this:

if (isset($_POST['button1'])) {
  // Do This was pressed
} else if (isset($_POST['button2'])) {
  // Do That was pressed
}

You can access the rest of your form’s elements in the same way (i.e. tick boxes, select options, text fields, etc).





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.