ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PHP Tutorial• 7 min read

Form Handling, Superglobals & Input Sanitization

Safely processing GET and POST submissions without XSS vulnerabilities

Superglobals are built-in variables always accessible from all scopes throughout your scripts. Handling form submissions requires strict validation and sanitization to prevent Cross-Site Scripting (XSS).

GET, POST, and Input Sanitization

$_POST: Collects data from HTML forms submitted with method="POST". Keeps sensitive data out of URL query strings.

$_GET: Collects data sent in URL query strings (e.g., ?search=term&page=2). Never use for credentials or state-changing actions.

htmlspecialchars(): Converts special characters (like <, >, &, ") into HTML entities, preventing malicious script injections.

filter_input(): Standardizes type casting and format validation for emails, integers, and URLs.

Secure Form Processing in PHP
<?php
  $errors = [];
  $email = "";

  if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Sanitize and validate email
    $rawEmail = trim($_POST["email"] ?? "");
    $email = filter_var($rawEmail, FILTER_SANITIZE_EMAIL);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $errors[] = "Please enter a valid business email address.";
    }

    if (empty($errors)) {
      // Safe to process or insert into database
      $safeName = htmlspecialchars($_POST["username"] ?? "Student");
      echo "<p class='success'>Thank you, " . $safeName . "! We have sent a confirmation to " . $email . "</p>";
    }
  }
?>
Always verify $_SERVER["REQUEST_METHOD"] before extracting POST parameters.
Warning / Pitfall

Never output unsanitized user input directly into HTML. An attacker can inject <script> tags to execute arbitrary JavaScript in victim browsers.

ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which function should you use to convert user input to safe HTML entities to neutralize XSS attacks?