PHP Web Development

Working with Forms in PHP: GET and POST Explained

Understand how HTML forms submit data with GET and POST, and how to validate and safely process submitted values in PHP.

Working with Forms in PHP

HTML forms let visitors submit information to a server. PHP can read submitted values, validate them, and decide what the application should do next. The two commonly used HTTP methods are GET and POST.

GET Requests

GET form values are appended to the URL as a query string. This is appropriate for retrieving or filtering information, such as a search query. Because values appear in the URL, GET should not be used for sensitive information.

POST Requests

POST sends form data in the request body rather than placing it in the URL. It is commonly used when submitting information that changes application state, such as creating a record. POST does not automatically encrypt data; use HTTPS to protect information in transit.

Reading Submitted Values

PHP exposes GET values through $_GET and POST values through $_POST. These are external inputs and must be treated as untrusted.

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = trim($_POST["email"] ?? "");
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Enter a valid email address.";
    }
}

Validation and Output Safety

Validate values on the server even if the browser also performs validation. Check required fields, length limits, formats, and allowed values. When displaying user-provided text in HTML, escape it with htmlspecialchars() to reduce cross-site scripting risks.

For forms that change data, also consider CSRF protection, authorization checks, and clear success or error messages. Use prepared statements when submitted values are stored in a database.

Conclusion

GET is generally suited to retrieving data, while POST is commonly used to submit changes. Neither method replaces validation, output escaping, HTTPS, or the other security controls an application needs.