Home >Backend Development >PHP Tutorial >How Can I Reliably Check for Form Submission in PHP?
To determine if a form has been submitted and thus should be validated, different approaches can be employed.
Initially considered was checking the existence of the $_POST superglobal:
isset($_POST)
However, this approach always returns true because superglobals are globally defined. Iterating through each form element is also not ideal:
if(isset($_POST['element1']) || isset($_POST['element2']) || isset(...etc)
A simpler solution involves adding a hidden flag field to check:
<!-- Form code here --> <input type="hidden" name="submitted" value="1">
// Check if the "submitted" field is set if (isset($_POST['submitted'])) { // Form has been submitted, validate input }
A more comprehensive approach involves checking the request method:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
This method is preferable because it also works in cases where checkboxes or buttons without names might not be present in the $_POST superglobal.
Note: It's important to consider potential edge cases where the request method may not be set to 'POST,' such as when the form is submitted without JavaScript.
The above is the detailed content of How Can I Reliably Check for Form Submission in PHP?. For more information, please follow other related articles on the PHP Chinese website!