R
Rishtaara
PHP Fundamentals
Lesson 13 of 32Article18 min

Form Handling & Validation

HTML forms send data to PHP using method="get" or method="post" and action="process.php". PHP reads fields from $_GET or $_POST.

PHP Form Handling

HTML forms send data to PHP using method="get" or method="post" and action="process.php". PHP reads fields from $_GET or $_POST.

Real-life example: A form is an order slip. The customer fills it; PHP is the kitchen that reads the slip and cooks the response.

HTML form + PHP handler
<!-- register.html -->
<form method="post" action="register.php">
  <label>Name: <input type="text" name="name" required /></label>
  <label>Email: <input type="email" name="email" required /></label>
  <button type="submit">Register</button>
</form>
register.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = trim($_POST["name"] ?? "");
  $email = trim($_POST["email"] ?? "");
  echo "Registered: " . htmlspecialchars($name) . " ($email)";
}
?>

Form Validation

Never trust user input. Check empty fields, correct formats, and length limits on the server — browser validation can be bypassed.

Real-life example: Validation is a security guard checking IDs at the door — friendly, but firm.

Server-side validation
<?php
$errors = [];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = trim($_POST["name"] ?? "");
  if ($name === "") {
    $errors[] = "Name is required.";
  } elseif (strlen($name) < 2) {
    $errors[] = "Name must be at least 2 characters.";
  }

  if ($errors) {
    foreach ($errors as $e) echo "<p style='color:red'>$e</p>";
  } else {
    echo "Valid submission!";
  }
}
?>