"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to determine PHP form button click

How to determine PHP form button click

Posted on 2025-04-13
Browse:439

How to Determine Which Form Button Was Clicked in PHP?

Determining Form Button Click in PHP

Identifying which button initiated a form submission can be crucial in PHP development. When multiple buttons coexist on a form, it becomes imperative to ascertain which one was clicked to facilitate appropriate backend actions.

Using an HTML form, such as:


PHP code can effectively determine the clicked button as follows:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Form submission detected

  if (isset($_POST['btnDelete'])) {
    // btnDelete clicked
  } else {
    // btnSubmit clicked or default button assumed
  }
}

Best Practices

To ensure proper form button detection, it's essential to:

  • Assume a default submit button: Always assume the first submit button appearing in the HTML source code is the default.
  • Only check for subsequent buttons explicitly: Only test for buttons that appear later in the form hierarchy.
  • Consider GET method: For forms submitted via GET, add a hidden input to indicate submission (e.g., ). Then, use isset($_GET['submitted']) to detect form submission.
  • Ensure browser compatibility: This strategy is widely supported by browsers, including older versions.

By adhering to these guidelines, developers can accurately determine which form button was clicked, enabling them to execute appropriate code responses based on user input.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3