XSS and CSRF
Escape with htmlspecialchars
Cross site scripting happens when user text is printed as page markup. Escape every untrusted value at the moment it enters HTML.
Function htmlspecialchars turns markup characters into safe entities. Always pass an explicit charset such as UTF-8.
echo htmlspecialchars($name, ENT_QUOTES, "UTF-8");
CSRF tokens
Cross site request forgery tricks a logged in browser into submitting a form the user never opened. A secret token proves the request came from your own form.
Generate a random token, store it in the session, and embed it in the form. Reject posts where the two values differ.
$token = bin2hex(random_bytes(32));
$_SESSION["csrf"] = $token;
echo $token;
SameSite cookies
SameSite tells the browser when to attach cookies to cross site requests. Lax blocks most forged posts while keeping normal links working.
Set it together with Secure and HttpOnly flags. Session cookies deserve all three on live sites.
session_set_cookie_params([
"samesite" => "Lax",
"secure" => true,
"httponly" => true,
]);
session_start();
echo "cookies set";
Security headers sketch
Extra response headers add a second layer of defense. They limit framing, sniffing, and risky content loading.
Send headers before any output. Start with a small strict set and relax it only when the application needs more.
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
echo "headers sent";
Next: SQL injection defense
Автор статьи: Arthur Isaev