Skip to content
← Back to Snippets
Code

Verify a Password

Verifies a submitted password against a stored PHP password hash and reports whether the hash should be upgraded.

Purpose

Verifies a submitted password against a stored PHP password hash and reports whether the hash should be upgraded.

Snippet details

ContextSecurityLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Verify a Password.
 *
 * Purpose:
 * Checks a submitted password against a stored password_hash() value and tells
 * the caller whether the stored hash needs rehashing.
 *
 * @param string $plain_password Password submitted by the user.
 * @param string $stored_hash Password hash stored in the database.
 * @return array Verification status and rehash recommendation.
 */
function ogSnippetVerifyAPassword(string $plain_password, string $stored_hash): array {
	if ($plain_password === '' || $stored_hash === '') {
		return array(
			'valid' => false,
			'needs_rehash' => false,
			'message' => 'Password and stored hash are required.'
		);
	}

	$valid = password_verify($plain_password, $stored_hash);
	$needs_rehash = false;

	if ($valid === true) {
		$needs_rehash = password_needs_rehash($stored_hash, PASSWORD_DEFAULT);
	}

	$message = 'Password is invalid.';

	if ($valid === true) {
		$message = 'Password verified.';
	}

	return array(
		'valid' => $valid,
		'needs_rehash' => $needs_rehash,
		'message' => $message
	);
}

/*
$hash = password_hash('SG1-Gate-Dial-Sequence-39', PASSWORD_DEFAULT);
$result = ogSnippetVerifyAPassword('SG1-Gate-Dial-Sequence-39', $hash);
print_r($result);
*/