0
0
PhpHow-ToBeginner · 3 min read

How to Validate Form in PHP: Simple Guide with Examples

To validate a form in PHP, check the submitted data using $_POST or $_GET and apply conditions like empty(), filter_var(), or regex to ensure inputs are correct. Use if statements to handle errors before processing the data.
📐

Syntax

Form validation in PHP typically involves checking the $_POST or $_GET superglobal arrays for submitted data. Use empty() to check if a field is filled, filter_var() to validate emails, and conditional statements to control the flow.

  • $_POST['field_name']: Access form data sent by POST method.
  • empty(): Checks if a variable is empty.
  • filter_var(): Validates data like emails.
  • if statements: To check conditions and handle errors.
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["username"])) {
        $error = "Username is required";
    } elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format";
    } else {
        $success = "Form is valid!";
    }
}
?>
💻

Example

This example shows a simple form with username and email fields. It validates that the username is not empty and the email is in a valid format. Errors are shown if validation fails, otherwise a success message appears.

php
<?php
$usernameErr = $emailErr = "";
$username = $email = "";
$success = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["username"])) {
        $usernameErr = "Username is required";
    } else {
        $username = htmlspecialchars($_POST["username"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format";
    } else {
        $email = htmlspecialchars($_POST["email"]);
    }

    if (empty($usernameErr) && empty($emailErr)) {
        $success = "Form is valid! Username: $username, Email: $email";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Form Validation</title>
</head>
<body>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        Username: <input type="text" name="username" value="<?php echo $username; ?>">
        <span style="color:red"><?php echo $usernameErr; ?></span><br><br>
        Email: <input type="text" name="email" value="<?php echo $email; ?>">
        <span style="color:red"><?php echo $emailErr; ?></span><br><br>
        <input type="submit" value="Submit">
    </form>
    <p style="color:green"><?php echo $success; ?></p>
</body>
</html>
Output
Form is valid! Username: John, Email: john@example.com
⚠️

Common Pitfalls

Common mistakes when validating forms in PHP include:

  • Not checking if the form was submitted before validating.
  • Not sanitizing user input, which can lead to security issues.
  • Using $_REQUEST instead of $_POST or $_GET, which can be less secure.
  • Not providing user feedback on errors.
php
<?php
// Wrong way: No check for form submission
if (empty($_POST["username"])) {
    echo "Username required";
}

// Right way: Check form submission first
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["username"])) {
        echo "Username required";
    }
}
?>
📊

Quick Reference

Tips for validating forms in PHP:

  • Always check $_SERVER['REQUEST_METHOD'] before processing.
  • Use empty() to check required fields.
  • Use filter_var() for emails and URLs.
  • Sanitize inputs with htmlspecialchars() before output.
  • Provide clear error messages to users.

Key Takeaways

Always check if the form is submitted using $_SERVER['REQUEST_METHOD'] before validating.
Use empty() and filter_var() to validate required fields and email formats.
Sanitize user inputs with htmlspecialchars() to prevent security risks.
Provide clear error messages to guide users in correcting input.
Avoid using $_REQUEST; prefer $_POST or $_GET for better control.