Forms and output safety

Read form data and stop cross-site scripting.

PHP
<?php
$name = trim($_POST["name"] ?? "");
$error = "";
if ($_SERVER["REQUEST_METHOD"] === "POST" && $name === "") {
    $error = "Name is required";
}
?>
<form method="post">
  <input name="name" value="<?= htmlspecialchars($name) ?>">
  <button>Save</button>
</form>
<p><?= htmlspecialchars($error) ?></p>

Wrap anything a user typed in htmlspecialchars before printing it. Otherwise an attacker can place scripts on your page.

Use $_POST to change data and $_GET only to read it.

โ† ArraysPHP and MySQL โ†’