Skip to content
← Back to Snippets
Code

Hash a Password

Creates a modern PHP password hash with password_hash() after enforcing a practical minimum password length.

Purpose

Creates a modern PHP password hash with password_hash() after enforcing a practical minimum password length.

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.
 */

/**
 * Hash a Password.
 *
 * Purpose:
 * Validates a plain-text password and hashes it with PHP's password_hash()
 * using the current PASSWORD_DEFAULT algorithm.
 *
 * @param string $plain_password Password supplied by a registration or reset form.
 * @return array Hash result and storage-ready password hash.
 */
function ogSnippetHashAPassword(string $plain_password): array {
	if (strlen($plain_password) < 12) {
		return array(
			'success' => false,
			'password_hash' => '',
			'message' => 'Password must be at least 12 characters.'
		);
	}

	$password_hash = password_hash($plain_password, PASSWORD_DEFAULT);

	if ($password_hash === false) {
		return array(
			'success' => false,
			'password_hash' => '',
			'message' => 'Password could not be hashed.'
		);
	}

	$hash_info = password_get_info($password_hash);

	return array(
		'success' => true,
		'password_hash' => $password_hash,
		'algorithm' => $hash_info['algoName'],
		'message' => 'Password hash created.'
	);
}

/*
$result = ogSnippetHashAPassword('Rocinante-Doors-And-Corners-47');
print_r($result);
*/