PHP: Security – code examples
Preventing XSS with htmlspecialchars
Security#xss#htmlspecialchars#escape#security
Use case: Output user comments, names or search terms into HTML safely.
<?php
function e(?string $s): string {
return htmlspecialchars($s ?? "", ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
$eingabe = '<img src=x onerror="alert(1)"> & "quote"';
echo "<p>Hello, " . e($eingabe) . "</p>\n";
echo '<a href="/suche?q=' . urlencode($eingabe) . '">Link</a>', "\n";Escape according to the context: htmlspecialchars for HTML text and attributes, urlencode for URL parameters. Without escaping, the browser executes the injected JavaScript.
Hashing and Verifying Passwords
Security#password_hash#password_verify#login#bcrypt
Use case: Registration and login: never store passwords in plain text.
<?php
$passwort = "secret123";
$hash = password_hash($passwort, PASSWORD_DEFAULT);
echo strlen($hash) >= 60 ? "Hash stored\n" : "Error\n";
var_dump(password_verify("secret123", $hash));
var_dump(password_verify("wrong", $hash));
var_dump(password_needs_rehash($hash, PASSWORD_DEFAULT));password_hash picks a secure algorithm, generates a salt and packs everything into one string. Store it in a VARCHAR(255) column. password_needs_rehash reports when you should renew the hash at the next login.
CSRF Token for Forms
Security#csrf#token#random_bytes#hash_equals
Use case: Prevent foreign websites from triggering actions (delete, pay) on your behalf.
<?php
session_start();
if (empty($_SESSION["csrf"])) {
$_SESSION["csrf"] = bin2hex(random_bytes(32));
}
function csrf_feld(): string {
return '<input type="hidden" name="csrf" value="' . htmlspecialchars($_SESSION["csrf"]) . '">';
}
function csrf_pruefen(): void {
$token = (string) ($_POST["csrf"] ?? "");
if (!hash_equals($_SESSION["csrf"], $token)) {
http_response_code(403);
exit("Invalid token");
}
}
echo csrf_feld();The token lives in the session and in the form; foreign sites do not know it. hash_equals compares in constant time (prevents timing attacks).