MasterPHP.in
PHP Tutorial

PHP Form Validation & Basic Security


Imagine a user submits:

  • Empty name
  • Invalid email
  • Malicious input like <script>alert('hack')</script>

Without validation and security:

  • Your app may break
  • Data becomes unreliable
  • You expose users to attacks (XSS)

Validation ensures correctness.

Security ensures safety.


1. Required Field Validation

Always validate before using form data.

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (empty($_POST['name'])) {
        echo "Name is required";
    } else {
        $name = htmlspecialchars($_POST['name']); // safe output
        echo "Hello " . $name;
    }
}

Key Concept

  • isset() → checks if field exists
  • empty() → checks if value is missing

Use empty() for validation.


2. What is $_SERVER["REQUEST_METHOD"]?

if ($_SERVER["REQUEST_METHOD"] === "POST")

This checks how the page was accessed.

  • Prevents validation from running before form submission
  • Ensures code runs only when form is submitted

3. isset() vs empty()

$name = $_POST['name'] ?? null;

if (isset($name)) {
    echo "Field exists";
}

if (!empty($name)) {
    echo "Field has value";
}

Difference:

  • isset() → field exists
  • empty() → field exists AND not empty


4. Preventing XSS (Input Sanitization)

Never output raw user input.

❌ Unsafe:

echo $_POST['name'];

If user enters:

<script>alert('Hacked')</script>

It executes in browser.

Safe Version

$name = htmlspecialchars($_POST['name']);
echo "Hello " . $name;

What happens:

  • < becomes &lt;
  • > becomes &gt;
  • Browser shows it as plain text
  • Script does NOT run


5. Complete Safe Form (Single File)

<?php
$name = "";
$error = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (empty($_POST['name'])) {
        $error = "Name is required";
    } else {
        $name = htmlspecialchars($_POST['name']);
    }
}
?>

<form method="post">
    <input type="text" name="name" placeholder="Enter your name">
    <button type="submit">Submit</button>
</form>

<?php
if ($error) {
    echo $error;
}

if ($name) {
    echo "Hello " . $name;
}
?>


6. Validating Multiple Fields (With Email Check)

<?php
$name = $email = "";
$error = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (empty($_POST['name']) || empty($_POST['email'])) {
        $error = "All fields are required";
    } else {
        $name = htmlspecialchars($_POST['name']);
        $email = htmlspecialchars($_POST['email']);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email format";
        }
    }
}
?>

<form method="post">
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <button type="submit">Submit</button>
</form>

<?php
if ($error) {
    echo $error;
} else if ($name && $email) {
    echo "Name: $name <br> Email: $email";
}
?>


7. GET Data is Also Unsafe

$search = htmlspecialchars($_GET['search'] ?? '');
echo "Searching for: " . $search;

Important:

GET and POST both come from users → always sanitize.


Common Mistakes (With Fix)

Mistake 1: Trusting User Input

echo $_POST['name'];

Fix:

echo htmlspecialchars($_POST['name']);

Mistake 2: Using Only isset()

if (isset($_POST['name'])) {
    echo "Valid";
}

Empty values still pass.

Fix:

if (!empty($_POST['name'])) {
    echo "Valid";
}

Mistake 3: No Validation Before Use

echo $_POST['email'];

Fix:

if (!empty($_POST['email'])) {
    echo htmlspecialchars($_POST['email']);
}


Practice Exercises

Task 1 (Easy)

Create a form with a name field and print greeting.

Test with:

Rohan

Expected Output:

Hello Rohan

Task 2 (Medium)

Create a form with name and email. Validate both fields and email format.


Test with:

Name: Amit
Email: amit@example.com

Expected Output:

Name: Amit
Email: amit@example.com

Task 3 (Hard)

Create a form with email and password. Validate both fields are not empty.

Note: This is only validation, not real authentication.

Test with:

Email: user@test.com
Password: 1234

Expected Output:

Form submitted: user@test.com


Summary

  • Always validate input using empty()
  • Use isset() to detect submission
  • Use $_SERVER["REQUEST_METHOD"] to control execution
  • Never trust user input
  • Always sanitize using htmlspecialchars()
  • Validate email using filter_var()
  • Apply security to both GET and POST

Share this tutorial