PHP Form Complete

Building a fully validated and secure form

✅ What is a Complete Form?

A complete PHP form combines all validation techniques, security measures, and user feedback into one functional system. It handles input safely, validates thoroughly, and provides clear error messages.


<?php
// Complete form processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate, sanitize, and process
}
?>
                                    

Complete Form Features

🔒

Security

Protect against XSS and injection

<?php
$safe = htmlspecialchars($input);
?>

Validation

Check all fields thoroughly

<?php
if (empty($name)) {
    $errors[] = "Name required";
}
?>
💬

Feedback

Show clear error messages

<?php
echo "<span class='error'>$error</span>";
?>
🔄

Persistence

Keep user input after errors

<input value="<?php echo $name; ?>">

🔹 Complete Contact Form Example

A fully functional form with all validation and security features:

<?php
// Initialize variables
$name = $email = $website = $comment = $gender = "";
$nameErr = $emailErr = $websiteErr = $genderErr = "";
$success = false;

// Process form on submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate name
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
            $nameErr = "Only letters and white space allowed";
        }
    }
    
    // Validate email
    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }
    
    // Validate website (optional)
    if (!empty($_POST["website"])) {
        $website = test_input($_POST["website"]);
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $website)) {
            $websiteErr = "Invalid URL";
        }
    }
    
    // Validate gender
    if (empty($_POST["gender"])) {
        $genderErr = "Gender is required";
    } else {
        $gender = test_input($_POST["gender"]);
    }
    
    // Get comment
    if (!empty($_POST["comment"])) {
        $comment = test_input($_POST["comment"]);
    }
    
    // Check if form is valid
    if (empty($nameErr) && empty($emailErr) && empty($websiteErr) && empty($genderErr)) {
        $success = true;
    }
}

// Sanitize and secure input
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

<!DOCTYPE html>
<html>
<head>
    <style>
        .error {color: #FF0000;}
        .success {color: #00AA00; padding: 10px; background: #E0FFE0; border: 1px solid #00AA00;}
        * {font-family: Arial, sans-serif;}
    </style>
</head>
<body>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>

<?php if ($success): ?>
    <div class="success">
        <h3>Form submitted successfully!</h3>
        <p><strong>Name:</strong> <?php echo $name; ?></p>
        <p><strong>Email:</strong> <?php echo $email; ?></p>
        <p><strong>Website:</strong> <?php echo $website; ?></p>
        <p><strong>Comment:</strong> <?php echo $comment; ?></p>
        <p><strong>Gender:</strong> <?php echo $gender; ?></p>
    </div>
<?php endif; ?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    Name: <input type="text" name="name" value="<?php echo $name; ?>">
    <span class="error">* <?php echo $nameErr; ?></span>
    <br><br>
    
    E-mail: <input type="text" name="email" value="<?php echo $email; ?>">
    <span class="error">* <?php echo $emailErr; ?></span>
    <br><br>
    
    Website: <input type="text" name="website" value="<?php echo $website; ?>">
    <span class="error"><?php echo $websiteErr; ?></span>
    <br><br>
    
    Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment; ?></textarea>
    <br><br>
    
    Gender:
    <input type="radio" name="gender" value="female" <?php if ($gender=="female") echo "checked"; ?>> Female
    <input type="radio" name="gender" value="male" <?php if ($gender=="male") echo "checked"; ?>> Male
    <input type="radio" name="gender" value="other" <?php if ($gender=="other") echo "checked"; ?>> Other
    <span class="error">* <?php echo $genderErr; ?></span>
    <br><br>
    
    <input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

🔹 Registration Form with Password

Complete registration form with password validation:

<?php
$username = $email = $password = $confirm = "";
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate username
    if (empty($_POST["username"])) {
        $errors['username'] = "Username is required";
    } else {
        $username = trim($_POST["username"]);
        if (strlen($username) < 3) {
            $errors['username'] = "Username must be at least 3 characters";
        }
    }
    
    // Validate email
    if (empty($_POST["email"])) {
        $errors['email'] = "Email is required";
    } else {
        $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = "Invalid email format";
        }
    }
    
    // Validate password
    if (empty($_POST["password"])) {
        $errors['password'] = "Password is required";
    } else {
        $password = $_POST["password"];
        if (strlen($password) < 6) {
            $errors['password'] = "Password must be at least 6 characters";
        }
    }
    
    // Validate confirm password
    if (empty($_POST["confirm"])) {
        $errors['confirm'] = "Please confirm password";
    } else {
        $confirm = $_POST["confirm"];
        if ($password !== $confirm) {
            $errors['confirm'] = "Passwords do not match";
        }
    }
    
    // If no errors, process registration
    if (empty($errors)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        echo "<p style='color:green;'>Registration successful!</p>";
        // Here you would save to database
    }
}
?>

<form method="post">
    Username: <input type="text" name="username" value="<?php echo $username; ?>">
    <span style="color:red;"><?php echo $errors['username'] ?? ''; ?></span>
    <br><br>
    
    Email: <input type="text" name="email" value="<?php echo $email; ?>">
    <span style="color:red;"><?php echo $errors['email'] ?? ''; ?></span>
    <br><br>
    
    Password: <input type="password" name="password">
    <span style="color:red;"><?php echo $errors['password'] ?? ''; ?></span>
    <br><br>
    
    Confirm Password: <input type="password" name="confirm">
    <span style="color:red;"><?php echo $errors['confirm'] ?? ''; ?></span>
    <br><br>
    
    <input type="submit" value="Register">
</form>

🔹 Form with File Upload

Complete form including file upload validation:

<?php
$name = "";
$nameErr = $fileErr = "";
$uploadSuccess = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate name
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = htmlspecialchars(trim($_POST["name"]));
    }
    
    // Validate file upload
    if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0) {
        $allowed = ["jpg" => "image/jpg", "jpeg" => "image/jpeg", "png" => "image/png"];
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
        
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if (!array_key_exists($ext, $allowed)) {
            $fileErr = "Please select a valid file format (JPG, JPEG, PNG)";
        }
        
        // Verify file size (5MB maximum)
        $maxsize = 5 * 1024 * 1024;
        if ($filesize > $maxsize) {
            $fileErr = "File size must be less than 5MB";
        }
        
        // Verify MIME type
        if (in_array($filetype, $allowed)) {
            if (empty($fileErr)) {
                $uploadSuccess = true;
                // Move uploaded file
                // move_uploaded_file($_FILES["photo"]["tmp_name"], "uploads/" . $filename);
            }
        } else {
            $fileErr = "Invalid file type";
        }
    } else {
        $fileErr = "Please select a file to upload";
    }
}
?>

<form method="post" enctype="multipart/form-data">
    Name: <input type="text" name="name" value="<?php echo $name; ?>">
    <span style="color:red;"><?php echo $nameErr; ?></span>
    <br><br>
    
    Photo: <input type="file" name="photo">
    <span style="color:red;"><?php echo $fileErr; ?></span>
    <br><br>
    
    <input type="submit" value="Upload">
</form>

<?php if ($uploadSuccess): ?>
    <p style="color:green;">File uploaded successfully!</p>
<?php endif; ?>

🔹 Form with Dropdown and Checkbox

Complete form with select dropdown and checkbox validation:

<?php
$name = $country = "";
$hobbies = [];
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate name
    if (empty($_POST["name"])) {
        $errors['name'] = "Name is required";
    } else {
        $name = htmlspecialchars(trim($_POST["name"]));
    }
    
    // Validate country
    if (empty($_POST["country"])) {
        $errors['country'] = "Please select a country";
    } else {
        $country = $_POST["country"];
    }
    
    // Validate hobbies (at least one required)
    if (empty($_POST["hobbies"])) {
        $errors['hobbies'] = "Please select at least one hobby";
    } else {
        $hobbies = $_POST["hobbies"];
    }
    
    // Process if no errors
    if (empty($errors)) {
        echo "<p style='color:green;'>Form submitted successfully!</p>";
    }
}
?>

<form method="post">
    Name: <input type="text" name="name" value="<?php echo $name; ?>">
    <span style="color:red;"><?php echo $errors['name'] ?? ''; ?></span>
    <br><br>
    
    Country:
    <select name="country">
        <option value="">Select...</option>
        <option value="USA" <?php if ($country=="USA") echo "selected"; ?>>USA</option>
        <option value="UK" <?php if ($country=="UK") echo "selected"; ?>>UK</option>
        <option value="Canada" <?php if ($country=="Canada") echo "selected"; ?>>Canada</option>
    </select>
    <span style="color:red;"><?php echo $errors['country'] ?? ''; ?></span>
    <br><br>
    
    Hobbies:<br>
    <input type="checkbox" name="hobbies[]" value="Reading" <?php if (in_array("Reading", $hobbies)) echo "checked"; ?>> Reading<br>
    <input type="checkbox" name="hobbies[]" value="Sports" <?php if (in_array("Sports", $hobbies)) echo "checked"; ?>> Sports<br>
    <input type="checkbox" name="hobbies[]" value="Music" <?php if (in_array("Music", $hobbies)) echo "checked"; ?>> Music<br>
    <span style="color:red;"><?php echo $errors['hobbies'] ?? ''; ?></span>
    <br><br>
    
    <input type="submit" value="Submit">
</form>

🔹 Security Best Practices

Essential security measures for complete forms:

Key Security Points:

  • Always use htmlspecialchars(): Prevents XSS attacks
  • Validate on server-side: Never trust client-side validation alone
  • Use prepared statements: When saving to database
  • Hash passwords: Use password_hash() function
  • Sanitize input: Remove unwanted characters
  • Use HTTPS: Encrypt data transmission
  • Implement CSRF protection: Use tokens for form submission
<?php
// Security example
$name = htmlspecialchars(trim($_POST["name"]));
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);

// CSRF token generation
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<form method="post">
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    <!-- Rest of form -->
</form>

🧠 Test Your Knowledge

Which function should you use to hash passwords in PHP?