Password Authentication
Password authentication is the most popular type of online user authentication.
The most secure way to perform password authentication is by hashing passwords using a one-way Cryptographic Hash Algorithm (specifically, a password-hashing algorithm such as Argon2id or bcrypt). Hashing is not encryption — it is a one-way function, so the stored hash cannot be reversed back to the original password.
The authentication process can be described in five steps.
- Hash the user’s preferred password (a fresh random salt is combined with the password so the resulting hash is unique per user).
- Store the hash with the user’s record in the database. Modern password-hash formats embed the algorithm, cost/work-factor parameters, and salt inside the hash string, so no separate columns are needed.
- User submits their username and password from a login page.
- Look up the stored hash for that username.
- Extract the salt and parameters from the stored hash, re-hash the attempted password with them, and compare the results in a constant-time manner. In PHP this is done in a single call to
password_verify().
It is not possible to recover the stored password from the hash because the hash function is one-way. Because each hash uses a fresh random salt, calling password_hash() twice on the same password produces two different hashes; verification therefore cannot compare hashes directly. Instead, the verifier reads the salt and parameters that were embedded in the stored hash and hashes the attempted password with those same values before comparing.
Password Authentication in PHP
PHP simplifies password authentication with the functions password_hash() and password_verify() (available since PHP 5.5; PHP 7.3+ is required for PASSWORD_ARGON2ID). These functions incorporate best practices for password hashing — they select a strong algorithm, generate a random salt, and embed it in the hash automatically. The preferred algorithm is PASSWORD_ARGON2ID; PASSWORD_DEFAULT uses PHP’s current default algorithm (bcrypt as of this writing) and may change in future PHP versions.
<?php
// Hashing (Argon2id recommended; requires PHP 7.3+ with Argon2 support)
$hashed_password = password_hash($password, PASSWORD_ARGON2ID);
// Verification example
$is_match = password_verify($attempted_password, $hashed_password);
?>