Security: XSS, SQL Injection, Passwords – PHP
The most important web attacks and how to prevent them in PHP.
Cross-site scripting (XSS): if you insert user text into HTML unchecked, an attacker can inject JavaScript. Rule: escape on output, appropriate to the context (HTML, attribute, URL, JS).
<?php
function e(?string $s): string {
return htmlspecialchars($s ?? "", ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
$kommentar = '<script>alert("xss")</script>';
echo "<p>" . e($kommentar) . "</p>";
// <p><script>alert("xss")</script></p>SQL injection: if you build input into SQL strings, you let attackers run their own commands. The solution is prepared statements – always, without exception.
<?php
// WRONG: name = ' OR '1'='1 returns all users
$pdo->query("SELECT * FROM nutzer WHERE name = '$name'");
// CORRECT
$stmt = $pdo->prepare("SELECT * FROM nutzer WHERE name = ?");
$stmt->execute([$name]);You never store passwords in plain text and never with md5/sha1. password_hash produces a salted, deliberately slow hash; password_verify checks it.
<?php
$passwort = "secret123";
$hash = password_hash($passwort, PASSWORD_DEFAULT); // e.g. $2y$10$... (60+ characters)
if (password_verify("secret123", $hash)) {
echo "Login OK\n";
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
$hash = password_hash("secret123", PASSWORD_DEFAULT); // store the new hash
}
}CSRF: a foreign site triggers an action using your logged-in session. Protection: a random token per session that every form sends along.
<?php
session_start();
if (empty($_SESSION["csrf"])) {
$_SESSION["csrf"] = bin2hex(random_bytes(32));
}
// In the form: <input type="hidden" name="csrf" value="<?= e($_SESSION["csrf"]) ?>">
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!hash_equals($_SESSION["csrf"], (string) ($_POST["csrf"] ?? ""))) {
http_response_code(403);
exit("Invalid CSRF token");
}
}File uploads: trust neither the file name nor the type reported by the browser. Check the size and the real MIME type, generate a name yourself and ideally store the file outside the web root.
<?php
$f = $_FILES["bild"] ?? null;
if ($f && $f["error"] === UPLOAD_ERR_OK && $f["size"] < 2_000_000) {
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($f["tmp_name"]);
$erlaubt = ["image/jpeg" => "jpg", "image/png" => "png"];
if (isset($erlaubt[$mime])) {
$ziel = __DIR__ . "/uploads/" . bin2hex(random_bytes(16)) . "." . $erlaubt[$mime];
move_uploaded_file($f["tmp_name"], $ziel);
}
}- Never
include/requirewith user input, nevereval(), neverunserialize()on foreign data - Randomness for tokens:
random_bytes()/random_int(), notrand()ormt_rand() - Secrets (DB password, API keys) in environment variables or
.envoutside the web root - Security headers:
Content-Security-Policy,X-Content-Type-Options: nosniff, enforce HTTPS - Keep dependencies up to date:
composer auditshows known vulnerabilities
< is not a security measure. Safety only comes from escaping on output and prepared statements when storing.