Explain it simply
PHP security in plain language
Security is not one big feature but a set of layers. A house is protected by a door, windows, locks and a dog, each stopping a different threat. PHP has a tool for each question too: can the incoming data be trusted, where is it going, and did the real user deliberately make this request?
The key is the attitude: treat everything that arrives from outside with suspicion, and choose the defence that matches where the data is used. Adding security afterwards is as awkward as building the house first and fitting the door later.
Problem → Why → Solution
The problem: four holes in nine lines
Picture a small comment page: it saves what a user writes in a database and prints it back, and it stores passwords with md5. It works fine in a quick test. But type x' OR '1'='1 as the user name and the SQL query changes meaning. Put a script tag in a comment and that script runs in every reader's browser. If the database leaks, md5 hashes can be reversed within minutes.
These are not exotic bugs. They all come from trusting a piece of text at a place where something will read it as code.
<?php
$user = $_POST['user'];
$comment = $_POST['comment'];
$pdo->query("INSERT INTO comments (user, body) VALUES ('$user', '$comment')");
echo "<p><b>$user</b>: $comment</p>"; // stored XSS
$hash = md5($_POST['password']); // fast and unsalted
$pdo->query("INSERT INTO users (name, pw) VALUES ('$user', '$hash')");Why one defence is never enough
Each hole sits in a different place: the SQL query, the HTML page and the password storage. htmlspecialchars protects only HTML and does nothing for SQL, and a prepared statement protects only SQL and does nothing for HTML. Every point on the data's journey therefore needs the defence that fits that point.
Core concept: one defence per place
Security becomes manageable as a list of questions: can this data be trusted (validate input), where is it going (escape output for that context), can it change my query (parameterized SQL), was this request deliberate (CSRF token, SameSite), who are you and are you allowed (passwords, sessions, authorization), and what leaks when something fails (never show internal error details). The table below pairs each threat with its defence and the PHP tool for it.
| Threat | Defence | PHP tool |
|---|---|---|
| SQL injection | parameterized queries | PDO prepare + execute |
| XSS | escape output per context | htmlspecialchars, rawurlencode, json_encode |
| CSRF | secret token plus SameSite | random_bytes, hash_equals |
| Leaked passwords | slow, salted hashing | password_hash, password_verify |
| Session theft | rotate the ID, cookie flags | session_regenerate_id, HttpOnly |
| Information leaks | hide errors, log them | display_errors=0, log_errors=1 |
SQL injection happens when user text is pasted into SQL text, so the database can no longer tell data from commands. A prepared statement sends the SQL with placeholders first and the values separately, so a value can only ever be a value. Use it for every value; but a placeholder cannot stand in for a table or column name, so pick those from an allow-list.
XSS happens when user-supplied text is printed into HTML and runs as markup or script in other visitors' browsers, where it can steal sessions or rewrite the page. Escape at output time with htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), and pick the function for where the value lands: rawurlencode inside a URL, json_encode (with the JSON_HEX flags) inside JavaScript. Validation does not replace escaping.
CSRF happens when a hostile site makes the visitor's browser submit a form to your site; the browser attaches the session cookie by itself, so the request looks legitimate. A random token stored in the session, embedded in every state-changing form and compared with hash_equals, proves the request came from your own page. For passwords, never store plaintext or a fast hash such as md5 or sha1. password_hash() adds a random salt and uses a deliberately slow algorithm, password_verify() checks it, and password_needs_rehash() tells you to upgrade a hash when your settings improve. Keep the column wide, such as VARCHAR(255), because the hash format may grow.
- Treat every outside value as hostile
- Validate it, then keep it as plain data
- Escape or bind it where it is used
- Check who is asking and why
Escape and bind at the place the data is used, not when it is received.
General pattern
$stmt = $pdo->prepare('... WHERE col = :name'); // values never touch the SQL
$stmt->execute([':name' => $value]);
echo htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$hash = password_hash($plain, PASSWORD_DEFAULT); // store this, never $plain
password_verify($plain, $hash); // check at login
hash_equals($known, $submitted); // compare secrets safelyBind values for SQL, escape on output for HTML, store and verify a hash for passwords, and compare secrets with hash_equals. Each one covers its own place and none can stand in for another.
Worked example: a safe login check
This sample uses an in-memory SQLite database and stores one user with a password hash. login() looks up the hash with a prepared statement and checks it with password_verify. It then tries a right password, a wrong password, an unknown user and one SQL injection attempt. Notice that the hash itself is never printed; only true and false are shown.
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL
)');
$sql = 'INSERT INTO users (email, password_hash) VALUES (:email, :hash)';
$insert = $pdo->prepare($sql);
$insert->execute([
':email' => 'ada@example.com',
':hash' => password_hash('correct horse', PASSWORD_DEFAULT),
]);
function login(PDO $pdo, string $email, string $password): bool
{
$stmt = $pdo->prepare('SELECT password_hash FROM users WHERE email = :email');
$stmt->execute([':email' => $email]);
$hash = $stmt->fetchColumn();
return is_string($hash) && password_verify($password, $hash);
}
$attempts = [
'right password' => ['ada@example.com', 'correct horse'],
'wrong password' => ['ada@example.com', 'wrong horse'],
'unknown user' => ['nobody@example.com', 'correct horse'],
'injection attempt' => ["x' OR '1'='1", 'anything'],
];
foreach ($attempts as $label => [$email, $password]) {
echo str_pad($label, 18), var_export(login($pdo, $email, $password), true), "\n";
}Code breakdown
- Exceptions on errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);With this setting a SQL mistake makes PDO throw an exception instead of failing silently. In production, write that exception's message to a log and never show it to the visitor.
- Hash before storing
':hash' => password_hash('correct horse', PASSWORD_DEFAULT),What reaches the database is a salted hash, not the plaintext password. Choosing PASSWORD_DEFAULT lets PHP use its currently recommended algorithm.
- Placeholder, not concatenation
$stmt = $pdo->prepare('SELECT password_hash FROM users WHERE email = :email');:email is only a placeholder. The SQL text is fixed and the email value travels separately through execute(), so a value full of quotes or the word OR cannot change the shape of the query.
- Verify, do not compare
return is_string($hash) && password_verify($password, $hash);When the user does not exist fetchColumn() returns false, so is_string() filters that out first. password_verify() compares the plaintext with the hash safely, so you never compare with === yourself.
- The attack just fails
'injection attempt' => ["x' OR '1'='1", 'anything'],The injection text is looked up as an ordinary email value, so no user matches and the result is false. What the same payload does through concatenation is shown in a later section.
right password true
wrong password false
unknown user false
injection attempt falseSeeing SQL injection safely
This demo runs on an in-memory database, so nothing real is harmed. unsafeFind() pastes the email straight into the SQL text, while safeFind() uses a placeholder. With a normal email both behave identically, but with the payload x' OR '1'='1 the unsafe version turns the WHERE clause into something always true and returns every user. The quote inside the payload closes the original string early and smuggles OR '1'='1' in as SQL.
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT)');
$pdo->exec("INSERT INTO users (email) VALUES ('ada@example.com')");
$pdo->exec("INSERT INTO users (email) VALUES ('linus@example.com')");
function unsafeFind(PDO $pdo, string $email): array
{
// the visitor's value is pasted into the SQL text
$sql = "SELECT email FROM users WHERE email = '$email'";
return $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);
}
function safeFind(PDO $pdo, string $email): array
{
$stmt = $pdo->prepare('SELECT email FROM users WHERE email = :email');
$stmt->execute([':email' => $email]);
return $stmt->fetchAll(PDO::FETCH_COLUMN);
}
$payload = "x' OR '1'='1";
echo 'unsafe, normal input : ', implode(', ', unsafeFind($pdo, 'ada@example.com')), "\n";
echo 'unsafe, payload : ', implode(', ', unsafeFind($pdo, $payload)), "\n";
echo 'safe, payload : ', count(safeFind($pdo, $payload)), " rows\n";unsafe, normal input : ada@example.com
unsafe, payload : ada@example.com, linus@example.com
safe, payload : 0 rowsDo not try to defend with an escaping function such as addslashes. How it behaves depends on the database and the character set, and forgetting it in one place reopens the hole. A placeholder separates SQL from values by construction, which is far sturdier.
XSS: escaping for the context
The same text has different dangerous characters depending on whether it lands in HTML, in a URL or in JavaScript. The example below escapes one string containing a script tag, an ampersand and quotes for all three places. In HTML the angle brackets, the ampersand and the quotes become entity codes, so the browser shows them as characters and no longer reads them as markup.
<?php
$name = '<script>x</script> & "q"';
echo 'HTML : ', htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), "\n";
echo 'URL : search.php?q=', rawurlencode('tea & milk'), "\n";
$flags = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
echo 'JS : var name = ', json_encode($name, $flags), ";\n";HTML : <script>x</script> & "q"
URL : search.php?q=tea%20%26%20milk
JS : var name = "\u003Cscript\u003Ex\u003C\/script\u003E \u0026 \u0022q\u0022";If you forget ENT_QUOTES, quotes inside an attribute stay unescaped and can break out of value="..." to inject a new attribute. ENT_SUBSTITUTE swaps malformed UTF-8 bytes for a replacement character instead of returning an empty string. Wrapping this in one helper such as e() makes it harder to forget.
CSRF tokens: issuing and checking
The token is generated with random_bytes so it cannot be guessed, kept in the session, and embedded as a hidden field in every state-changing form. Another site cannot read your page, so it cannot learn the token. This sample uses a plain array in place of $_SESSION so it works on the command line, which has no session; on a real page you would use $_SESSION there after session_start(). The token itself is never printed, only its length and the comparison results.
<?php
// A plain array stands in for $_SESSION here; real pages use $_SESSION.
$session = [];
function csrfToken(array &$session): string
{
if (!isset($session['csrf'])) {
$session['csrf'] = bin2hex(random_bytes(32));
}
return $session['csrf'];
}
function csrfValid(array $session, ?string $submitted): bool
{
return isset($session['csrf'])
&& is_string($submitted)
&& hash_equals($session['csrf'], $submitted);
}
$token = csrfToken($session);
echo 'token length : ', strlen($token), "\n";
echo 'same token on reload : ', var_export(csrfToken($session) === $token, true), "\n";
echo 'form sends the token : ', var_export(csrfValid($session, $token), true), "\n";
echo 'forged, no token : ', var_export(csrfValid($session, null), true), "\n";
$guess = str_repeat('0', 64);
echo 'forged, guessed token : ', var_export(csrfValid($session, $guess), true), "\n";token length : 64
same token on reload : true
form sends the token : true
forged, no token : false
forged, guessed token : false<form method="post" action="/transfer">
<input type="hidden" name="csrf" value="<?= htmlspecialchars($token) ?>">
<button type="submit">Send money</button>
</form>hash_equals() decides equal or not in constant time, so unlike === it does not stop at the first mismatching character, and response time reveals nothing about how many characters were right. A GET request should also never change state, or a plain link with no token check can cause damage. SameSite cookies reduce CSRF risk but do not replace the token.
Storing passwords, and why md5 is not an option
md5 and sha1 were designed to be fast, for jobs such as checking files, which is exactly what an attacker wants when guessing millions of passwords per second. With no salt, equal passwords give equal hashes and precomputed tables find them instantly. password_hash() adds a fresh random salt on every call, so two hashes of the same password differ, yet password_verify() accepts both.
<?php
function show(string $label, bool $answer): void
{
echo str_pad($label, 26), var_export($answer, true), "\n";
}
$password = 'correct horse battery staple';
$hash1 = password_hash($password, PASSWORD_DEFAULT);
$hash2 = password_hash($password, PASSWORD_DEFAULT);
show('right password verifies', password_verify($password, $hash1));
show('wrong password verifies', password_verify('wrong', $hash1));
show('same password, same hash', $hash1 === $hash2);
show('second hash also verifies', password_verify($password, $hash2));
show('md5 repeats itself', md5($password) === md5($password));
$costly = ['cost' => 14];
show('needs rehash at cost 14', password_needs_rehash($hash1, PASSWORD_BCRYPT, $costly));right password verifies true
wrong password verifies false
same password, same hash false
second hash also verifies true
md5 repeats itself true
needs rehash at cost 14 trueCall password_needs_rehash() after a successful login: if it returns true, make a new hash from the plaintext you just received and replace the stored one. That upgrades security without bothering users. Never print a hash in a log, an error message or a page.
In real projects
Security in real projects
Registration and login, search boxes, comments and reviews, admin panels and file uploads all use every defence above. Frameworks supply most of them by default: Laravel's @csrf and Blade's {{ }} auto-escaping, parameter binding in Eloquent and Doctrine, and Symfony's password hasher. Wherever you bypass the framework, with a raw query or raw unescaped output, the responsibility is yours again.
On production turn display_errors off and log_errors on, so error details such as paths and SQL are visible to you but not to readers. Keep secrets such as database passwords and API keys out of the repository and in environment variables. The OWASP Top 10 is a useful checklist of which threats to look at first.
Common mistakes
Common mistakes with security
Escaping for SQL instead of binding
addslashes() or hand-rolled quote replacement leaves a hole the moment you forget it in one place. Bind every value with a placeholder.
HTML-escaping on input and storing the result
Storing already-escaped text leads to double escaping later in JSON, email or PDF, and it does not protect the other places either. Store the data as typed and escape at output time.
Storing passwords with md5, sha1 or plaintext
A fast hash helps the attacker. Use password_hash() and password_verify() only, and keep the column wide, such as VARCHAR(255).
Weak token generation and === comparison
Tokens made with rand(), uniqid() or time() can be guessed. Generate them with random_bytes() and compare with hash_equals().
Believing one defence is enough
htmlspecialchars stops XSS only; it does nothing for SQL injection, CSRF or missing authorization checks. Each threat needs its own tool.
Showing detailed errors on production
With display_errors=1 readers see paths, SQL and stack traces, which is a map for an attacker. Write details to the log and show readers one generic message.
Best practices
Best practices
- Bind every SQL value with a PDO placeholder and choose table and column names from an allow-list.
- Escape every output for its context, and keep one helper such as e() for HTML in a single place.
- Put a CSRF token in every state-changing form and set cookies with HttpOnly, Secure and SameSite.
- Store passwords with password_hash, check password_needs_rehash at login, and return the same message for an unknown user and a wrong password.
Mini challenge
Mini challenge: a safe guestbook
Write four functions for a guestbook: e() escapes HTML output, csrfToken() issues a token once and keeps it in a session array, csrfValid() checks with hash_equals, and addEntry() stores one entry with a prepared statement. Try one valid post and one forged post without a token, then print the stored entries through e().
- e() uses ENT_QUOTES | ENT_SUBSTITUTE and UTF-8
- csrfToken() runs bin2hex(random_bytes(32)) and only on the first call
- csrfValid() returns false, without an error, when the token is missing
- addEntry() inserts with named placeholders; print the outcome of both posts and show the stored entries through e()
<?php
function e(string $text): string
{
// TODO: escape for HTML output (quotes included, UTF-8)
}
function csrfToken(array &$session): string
{
// TODO: create a 32-byte random token once and keep it in $session['csrf']
}
function csrfValid(array $session, ?string $submitted): bool
{
// TODO: use hash_equals, and cope with a missing token
}
function addEntry(PDO $pdo, string $name, string $message): void
{
// TODO: INSERT with a prepared statement and named placeholders
}
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE entries (id INTEGER PRIMARY KEY, name TEXT, message TEXT)');
$session = [];
// TODO: simulate a valid post and a forged post; store only the valid one
// TODO: print every stored entry as a paragraph, escaped with e()Expected: The first post prints stored, the forged one is rejected for its CSRF token, and the stored message appears in a paragraph with its angle brackets, ampersand and quotes turned into entity codes.
Show hint
Inside csrfValid, check isset($session['csrf']) and is_string($submitted) before calling hash_equals, because both of its arguments must be strings. Use PDO::FETCH_ASSOC when you read the rows back.
Show solution
<?php
function e(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function csrfToken(array &$session): string
{
if (!isset($session['csrf'])) {
$session['csrf'] = bin2hex(random_bytes(32));
}
return $session['csrf'];
}
function csrfValid(array $session, ?string $submitted): bool
{
return isset($session['csrf']) && is_string($submitted)
&& hash_equals($session['csrf'], $submitted);
}
function addEntry(PDO $pdo, string $name, string $message): void
{
$sql = 'INSERT INTO entries (name, message) VALUES (:name, :message)';
$stmt = $pdo->prepare($sql);
$stmt->execute([':name' => $name, ':message' => $message]);
}
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE entries (id INTEGER PRIMARY KEY, name TEXT, message TEXT)');
$session = [];
$token = csrfToken($session);
$posts = [
[
'csrf' => $token,
'name' => 'Ada',
'message' => '<script>alert(1)</script> & "hi"',
],
['name' => 'Mallory', 'message' => 'I never saw your form'],
];
foreach ($posts as $number => $post) {
$label = 'post ' . ($number + 1);
if (!csrfValid($session, $post['csrf'] ?? null)) {
echo "$label: rejected (bad CSRF token)\n";
continue;
}
addEntry($pdo, $post['name'], $post['message']);
echo "$label: stored\n";
}
$rows = $pdo->query('SELECT name, message FROM entries')->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo '<p><b>', e($row['name']), '</b>: ', e($row['message']), "</p>\n";
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Security is layered: PDO prepared statements for SQL, output escaping for HTML, a token for CSRF and password_hash for passwords, and none replaces another.
- Stop SQL injection by binding every value with a placeholder and choosing table and column names from an allow-list.
- Stop XSS by escaping at the point of output with htmlspecialchars, rawurlencode or json_encode, depending on the context.
- Make CSRF tokens with random_bytes and check them with hash_equals, store passwords with password_hash rather than md5, and never display a hash.
PHP Security Manual — PHP Documentation Group