CodeBlanks Logo Icon CodeBlanks

Summary - Security

PHP course · Advanced · Lesson 66/92

Build a secure login form with password_hash, htmlspecialchars and CSRF.

Summary - Security tools

In this group you learned four key security tools. With password_hash you store passwords safely; with password_verify you validate them. htmlspecialchars prevents XSS and prepare prevents SQL injection.

CSRF tokens block forged form submissions; you verify them with hash_equals against timing attacks. Now let us combine these tools into a secure login check.

Exercise Write a secure login check

Define a verifyLogin($password, $csrf, $hash) function. Inside it, verify the CSRF token with hash_equals($_SESSION['csrf_token'], $csrf); return false if it does not match. Then verify the password with password_verify($password, $hash). $hash and $_SESSION['csrf_token'] are already defined. Call verifyLogin with the correct password and the correct CSRF; print the result as "valid" or "invalid".

Show example solution
"invalid") . "\n";.
Example solution:
<?php
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));
$storedHash = password_hash("gizli123", PASSWORD_DEFAULT);
function verifyLogin($password, $csrf, $hash) {
    if (!hash_equals($_SESSION['csrf_token'], $csrf)) {
        return false;
    }
    return password_verify($password, $hash);
}
$ok = verifyLogin("gizli123", $_SESSION['csrf_token'], $storedHash);
echo ($ok ? "valid" : "invalid") . "\n";

Test yourself

  1. What is the safe way to store passwords in the database?

    • As plain text
    • Hashed with md5
    • password_hash + PASSWORD_DEFAULT
    • With base64_encode
    Show answer

    password_hash + PASSWORD_DEFAULT — Correct. password_hash + PASSWORD_DEFAULT is the safe, modern choice.

  2. Print the username safely

    echo ____($username, ENT_QUOTES, "UTF-8") . "
    ";
    Show answer
    echo htmlspecialchars($username, ENT_QUOTES, "UTF-8") . "
    ";
  3. Match each defense to its attack

    password_hash
    Against password leak
    htmlspecialchars
    Against XSS attack
    hash_equals
    Against CSRF forgery
    prepare
    Against SQL injection

All lessons in Advanced