← PHP for real applications
04 / 8 · 23 MIN

Security at the web boundary

Handle passwords, HTML output, and errors carefully.

Storing passwords

Use password_hash and password_verify rather than storing a password or a simple fast hash. Limit authentication attempts, protect session cookies, and invalidate sessions when necessary. HTTPS protects data in transit.

Displaying external data

When inserting user text into HTML, encode it for that context, for example with htmlspecialchars. Do not show stack traces or database details on public pages. Record enough operational information in a restricted channel and show a useful user message.

Guided workplace application

On a profile page, the name should appear as text inside a paragraph. Apply htmlspecialchars with explicit flags and encoding at that output point; do not assume PDO storage makes the string safe in every context. JavaScript, CSS, and URLs have different rules, and the simplest option is often to avoid concatenating data into executable code. For authentication, verify the password using password_verify and the stored hash. Two password_hash outputs for the same input may differ because of salt, so literal comparison is not an authentication method. After successful verification, password_needs_rehash helps decide a parameter upgrade. On failure return an appropriate message with a reference and retain sanitized diagnostics in access-controlled records.

$safeName = htmlspecialchars(
 $name, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"
);
echo "<p>". $safeName. "</p>"
IN PRACTICE

A name contains HTML characters. The page should display that text as data rather than execute it as markup or script.

Common pitfalls

Comparing newly generated hashes; applying HTML encoding to every context; exposing internal diagnostics.

Related topics: PDO transactions and partial failures · HTTP, sessions, and per-resource authorization

Take this idea with you

Protect credentials, encode output for the right context, and limit error exposure.

Create account

Reference: PHP manual: htmlspecialchars · PHP 8.5 reference; DR PHP 2026.2; new fixtures executed on PHP 8.3.17