XSS and CSRF
Two attacks share one habit: a value from outside the program is trusted where it is used. The escaping call of PHP keeps text out of HTML, and a session token keeps a foreign form out of your own posts. Each example below was run here, the web ones through php -S.
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.
<?php $name = "<script>alert(1)</script>"; echo htmlspecialchars($name, ENT_QUOTES, "UTF-8"), PHP_EOL; echo $name, PHP_EOL;
php escape.php
<script>alert(1)</script>
<script>alert(1)</script>
The first line is what a browser shows as text, and the second one is what it would run as a script. The two lines in the output are the difference between a value and markup. An attacker's JavaScript runs inside the page of the victim, which is why escaping belongs at every place a value leaves into HTML.
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.
The token comes from random_bytes() rather than
rand(), because a guessable token proves nothing.
The file token.php in the folder you serve with php -S 127.0.0.1:8000:
<?php session_start(); $token = bin2hex(random_bytes(32)); $_SESSION["csrf"] = $token; echo strlen($token), PHP_EOL; echo hash_equals($_SESSION["csrf"], $token) ? "token ok" : "token differs", PHP_EOL;
curl -s "http://127.0.0.1:8000/token.php"
64
token ok
Thirty-two random bytes become 64 hex characters, and the comparison passes because the form sent the stored value back. The check uses hash_equals(), which compares in constant time, so a guess learns nothing from the duration of the answer.
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.
The file samesite.php in the same folder:
<?php session_set_cookie_params([ "samesite" => "Lax", "secure" => true, "httponly" => true, ]); session_start(); echo "cookies set", PHP_EOL;
curl -s "http://127.0.0.1:8000/samesite.php"
cookies set
The response carries Set-Cookie: PHPSESSID=...; path=/; secure; HttpOnly; SameSite=Lax, all three flags in one line. A form posted from another site arrives without this cookie, so the session is not the victim's.
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.
The file headers.php in the same folder:
<?php header("X-Content-Type-Options: nosniff"); header("X-Frame-Options: DENY"); echo "headers sent", PHP_EOL;
curl -s "http://127.0.0.1:8000/headers.php"
headers sent
The response of the run carries X-Content-Type-Options: nosniff and X-Frame-Options: DENY beside the body. The first stops a browser from guessing a type, the second stops another site from framing this page.
Exercises
- Print a name with a quote in it through htmlspecialchars() with and without ENT_QUOTES.
- Compare two tokens of different length with hash_equals() and read what it returns.
- Set "samesite" => "Strict" and describe which link stops working.
- Add a third header of your choice to the sketch and confirm it in the response with curl -sI.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where does escaping belong in an application?
Answer
At the moment a value goes into HTML
One value may be safe in HTML and unsafe in a shell or a query, so the escaping belongs to the place that uses it.
-
What does
ENT_QUOTESadd tohtmlspecialchars()?Answer
It escapes single and double quotes as well
Without the flag only the double quote is escaped, and a value that lands inside an attribute needs both.
-
Why does the token come from
random_bytes()rather thanrand()?Answer
It is unpredictable, while
rand()is notA token that a guesser can predict is no proof, and
random_bytes()is built for secrets. -
What does
SameSite=Laxstop?Answer
A form on another site posting with the session cookie attached
A cross-site POST arrives without the cookie, while a normal top-level link still carries it.
-
What does this program print?
<?php echo htmlspecialchars("<b>hello</b>", ENT_QUOTES, "UTF-8");Answer
<b>hello</b>
Each angle bracket becomes an entity, so a browser shows the tags as text.
-
What does this program print?
<?php var_dump(hash_equals("abc", "abd"));Answer
bool(false)
The strings differ in one byte, so the comparison reports false.
-
What does this program print?
<?php $token = bin2hex(random_bytes(16)); echo strlen($token);Answer
32
Every byte becomes two hex characters, so sixteen bytes take 32 characters.
-
What does this program print?
<?php $stored = "abc123"; $sent = $stored; if (hash_equals($stored, $sent)) { echo "token ok"; } else { echo "token differs"; }Answer
token ok
The two values are equal, so the form is accepted.
-
Why is comparing tokens with
==a weakness?Answer
It stops at the first different byte, so the time leaks the match length
A short-circuiting comparison tells an attacker how much of a guess was right;
hash_equals()takes the same time either way. -
A page reads
$_GET["next"]and prints it into a link. What is the fix?Answer
Escape it with
htmlspecialchars()where it is printed, and check that the target is allowedEscaping keeps it text, and an allow-list keeps a redirect from leaving the site.
The examples call htmlspecialchars(), random_bytes(), bin2hex() and hash_equals(). The programs on this page were run with PHP 8.5.13 (php -v), the web ones with php -S 127.0.0.1:8000.
Article author: Arthur Isaev