How to test which HTML form button was pressed in PHP

- by

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:

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).

Add your voice!

This site uses Akismet to reduce spam. Learn how your comment data is processed.