Tools
Log in
English

Learn to codePHP

PHP security basics

Based on PHP 8.3

Seven PHP security fixes: escaping, PDO, password_hash, CSRF, uploads.

Seven things to lock down first in PHP web code

Most PHP code takes values sent by a browser and builds HTML from them. Three habits prevent nearly every incident: filter on the way in, escape on the way out, and hand values to the database separately.

Each item shows wrong code next to fixed code. Where output is shown, it was really run on server PHP and browser PHP; items that need a database, a session or an upload were syntax checked only.

Before you deploy

  • Every echo and <?= goes through e() (htmlspecialchars)
  • No variable is glued into SQL (prepare only)
  • Passwords are stored with password_hash() only
  • State-changing POST forms carry a CSRF token
  • Uploads live outside the web root under random names
  • The session cookie is secure, httponly and samesite
  • display_errors is off in production (errors go to a log file)

1Filtering input

Everything that arrives through $_GET or $_POST is a string. When PHP 8 compares the non-numeric string '20abc' with the number 19, it turns 19 into a string and compares strings, so the check passes by accident.

Wrong

<?php$input = ['age' => '20abc']; if ($input['age'] > 19) {    echo "adult\n";} else {    echo "minor\n";}

When you run itadult

Fixed

<?php$input = ['age' => '20abc']; $age = filter_var($input['age'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 150]]);if ($age === false) {    echo "invalid age\n";} else {    echo $age > 19 ? "adult\n" : "minor\n";}

When you run itinvalid age

Use filter_var() with FILTER_VALIDATE_INT to ask "is it an integer, and in range?" first, and stop on failure (false). Pass only the filtered value on. The example fakes $_GET with an $input array.

Run on server and browser

2Escaping output

If a user types <script> as their name, echoing it turns it into HTML that runs in other people’s browsers (XSS). Filtering input is not enough; escape every time you print.

Wrong

<?php$name = '<script>alert(1)</script>'; echo "<p>Hello, $name</p>\n";

When you run it<p>Hello, <script>alert(1)</script></p>

Fixed

<?php$name = '<script>alert(1)</script>'; function e(string $s): string{    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');} echo '<p>Hello, ' . e($name) . "</p>\n";

When you run it<p>Hello, &lt;script&gt;alert(1)&lt;/script&gt;</p>

htmlspecialchars() turns < > & " ' into harmless text. ENT_QUOTES covers single quotes and ENT_SUBSTITUTE handles broken byte sequences. Wrap it in a short e() helper and use it for all output so nothing slips through.

Run on server and browser

3SQL through prepared statements (PDO prepare)

Gluing a value into the SQL text lets one quote change the condition. The SQL built by the wrong code gains OR '1'='1' and returns every user (SQL injection).

Wrong

<?php$name = "x' OR '1'='1"; $sql = "SELECT id, name FROM users WHERE name = '$name'";echo $sql, "\n";

When you run itSELECT id, name FROM users WHERE name = 'x' OR '1'='1'

Fixed

<?phpfunction findUsers(PDO $pdo, string $name): array{    $stmt = $pdo->prepare('SELECT id, name FROM users WHERE name = ?');    $stmt->execute([$name]);    return $stmt->fetchAll(PDO::FETCH_ASSOC);} $pdo = new PDO('mysql:host=localhost;dbname=app;charset=utf8mb4', 'app', getenv('DB_PASS') ?: '', [    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,    PDO::ATTR_EMULATE_PREPARES => false,]);$rows = findUsers($pdo, "x' OR '1'='1");

Send SQL with placeholders (?) through prepare() first and pass values separately with execute([...]). The values are never read as SQL. Things that cannot be placeholders, such as table or sort column names, should come from a fixed allow list. The fixed code needs a database, so here it was only syntax checked.

Run on server and browser

4Passwords with password_hash

md5() and sha1() are fast, so common passwords can be guessed quickly, and the same password always gives the same value. The md5 value above can be looked up online in seconds.

Wrong

<?php$hash = md5('hunter2'); echo $hash, "\n";echo $hash === md5('hunter2') ? "login ok\n" : "login failed\n";

When you run it2ab96390c7dbe3439de74d0c9b0b1767 login ok

Fixed

<?php$hash = password_hash('hunter2', PASSWORD_DEFAULT); var_dump(password_verify('hunter2', $hash));var_dump(password_verify('hunter3', $hash));var_dump(password_get_info($hash)['algoName']);

When you run itbool(true) bool(false) string(6) "bcrypt"

password_hash() uses a deliberately slow calculation and a random salt, so even the same password hashes differently every time. Check with password_verify() only and give the database column 255 characters. PASSWORD_DEFAULT may move to a stronger algorithm in later PHP versions; re-save with password_needs_rehash().

Run on server and browser

5CSRF tokens

A logged-in user visits another site, and that site quietly posts a form to our transfer address. The browser attaches our cookie, and the wrong code trusts the request.

Wrong

<?phpsession_start(); if ($_SERVER['REQUEST_METHOD'] === 'POST') {    transferMoney($_SESSION['user_id'], $_POST['to'], (int)$_POST['amount']);}

Fixed

<?phpsession_start();$_SESSION['csrf'] ??= bin2hex(random_bytes(32)); if ($_SERVER['REQUEST_METHOD'] === 'POST') {    if (!hash_equals($_SESSION['csrf'], (string)($_POST['csrf'] ?? ''))) {        http_response_code(403);        exit('bad form token');    }    transferMoney($_SESSION['user_id'], $_POST['to'], (int)$_POST['amount']);} $token = htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8');echo '<form method="post"><input type="hidden" name="csrf" value="' . $token . '">...</form>';

Create a hard-to-guess token per session (random_bytes), hide it in every form and compare it on submit with hash_equals(). Other sites cannot read the token. Combine it with the SameSite cookie setting for extra safety.

Syntax checked only (needs a database, session or request)

6Checking uploads

The type and file name in $_FILES are whatever the sender claims. Disguise shell.php as an image, drop it into a web folder, and anyone can run it on the server by opening its URL.

Wrong

<?php$name = $_FILES['photo']['name']; if ($_FILES['photo']['type'] === 'image/png') {    move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/uploads/' . $name);}

Fixed

<?php$f = $_FILES['photo'] ?? null;if (!is_array($f) || $f['error'] !== UPLOAD_ERR_OK || $f['size'] > 2 * 1024 * 1024) {    exit('upload failed');}$mime = (new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);$ext = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp'][$mime] ?? null;if ($ext === null) {    exit('only png, jpg or webp');}$dir = dirname(__DIR__) . '/storage/uploads';$file = bin2hex(random_bytes(16)) . '.' . $ext;move_uploaded_file($f['tmp_name'], $dir . '/' . $file);

Check the error code and size first, detect the real type from the contents (finfo), and attach only an extension from your own list. Generate a random file name and store it outside the web root (public), serving it through PHP.

Syntax checked only (needs a database, session or request)

7Session cookie settings

With default settings the session cookie may be readable from JavaScript (no httponly) or travel over plain http. If the session id stays the same across login, someone who planted that id beforehand can ride the logged-in session (session fixation).

Wrong

<?phpsession_start(); if (checkLogin($_POST['email'], $_POST['password'])) {    $_SESSION['user_id'] = findUserId($_POST['email']);}

Fixed

<?phpsession_set_cookie_params([    'lifetime' => 0,    'path' => '/',    'secure' => true,    'httponly' => true,    'samesite' => 'Lax',]);session_start(); if (checkLogin($_POST['email'], $_POST['password'])) {    session_regenerate_id(true);    $_SESSION['user_id'] = findUserId($_POST['email']);}

Turn on secure, httponly and samesite before session_start(), and call session_regenerate_id(true) right after a successful login. On logout, call session_destroy() and clear the cookie too.

Syntax checked only (needs a database, session or request)

Questions people ask

If input is filtered, do I still need to escape output?

Yes. Filtering checks that a value is valid; escaping keeps it from being read as HTML. Use htmlspecialchars on every output.

Is mysqli_real_escape_string good enough?

It is easy to forget and useless outside quotes. Prepared statements in PDO or mysqli, which pass values separately, are safer.

How long should the password column be?

password_hash output is 60 characters today, but algorithms can change, so allow 255.