Home > Backend Development > PHP Tutorial > How Can I Reliably Check for Form Submission in PHP?

How Can I Reliably Check for Form Submission in PHP?

Barbara Streisand
Release: 2024-12-05 09:42:10
Original
211 people have browsed it

How Can I Reliably Check for Form Submission in PHP?

Checking 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)
Copy after login

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)
Copy after login

A simpler solution involves adding a hidden flag field to check:

<!-- Form code here -->
<input type="hidden" name="submitted" value="1">
Copy after login
// Check if the "submitted" field is set
if (isset($_POST['submitted'])) {
    // Form has been submitted, validate input
}
Copy after login

Cleaner Alternative

A more comprehensive approach involves checking the request method:

if ($_SERVER['REQUEST_METHOD'] == 'POST')
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template