Detect which submit button is clicked when a form is submitted

detect-submit-button-is-clicked-when-a-form-is-submitted-using-php

We may have a case when we have multiple submit button and we want to detect which button is clicked. In this article, we will see how to detect which submit button is clicked when a form is submitted using PHP language.

The PHP isset() function is used to check whether a variable is set or not. The isset() function returns boolean (true or false). So, we can detect the click of submit button using the PHP isset() function.

When a submit button is clicked via mouse button or keyboard’s enter button, the browser sends the name and value of the button safely when POST method is used.

Let’s assign a unique name to each submit button, if you use same names then you will get invalid results.

The HTML of form is:

<input type="submit" name="button_reset" value="Reset" />
<input type="submit" name="button_save" value="Save" />
<input type="submit" name="button_delete" value="Delete" />

Now that we have assigned unique names to each input now we need to write some PHP code.

The PHP code would look like:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['button_reset'])) {
        // reset button is clicked
    } 
    else if (isset($_POST['button_save'])) {
        // save button is clicked
    } 
    else if (isset($_POST['button_delete'])) {
       // delete button is clicked
    } 
    else {
        // display error e.g. invalid form submission or access denied
    }
}
?>

The “else” part will handle the requests that are not coming from the form. It is highly recommended to apply security and sanitization on forms to prevent attackers. The good practise is to always have an else part for each “if” statement to handle the exceptions.

When an invalid request is sent through the form, the form controller should handles the error. In this way you can apply one-level security on your form which will accept only the actual request and invalid request will be discarded.

See how to apply CSRF in the PHP application.

Related Posts