Hash Passwords Safely with password_hash()

Hash passwords with PASSWORD_DEFAULT

Let PHP generate the salt automatically. PASSWORD_DEFAULT is designed to evolve, so store hashes in a column that can comfortably grow, such as VARCHAR(255).

<?php
$password = 'correct horse battery staple';
$hash = password_hash($password, PASSWORD_DEFAULT);

echo $hash;
?>

Current example first; the detailed tutorial examples below are retained for additional learning and comparison.

$str="plus2net.com";
$str_hash=password_hash($str,PASSWORD_DEFAULT);
echo $str_hash;
Output is here
$2y$10$/r1bsR9lXZ52gYPmeH69Bu3.k0ABji7ZJdiZTPmUWEAgaQpkBkfKq
Syntax
password_hash('$string',$alog,$options);
ParameterDESCRIPTION
$stringRequired : Input password string variable
$alogRequired : algorithms to be used.
$options Optional : An associative array containing options.

Algorithms supported

PASSWORD_DEFAULT : currently maps to bcrypt, but it is designed to change over time. Store password hashes in a column large enough for future algorithms; 255 bytes is a practical choice
PASSWORD_BCRYPT : CRYPT_BLOWFISH to create the hash. Output 60 chars legth
PASSWORD_ARGON2I : Argon2i hashing algorithm
PASSWORD_ARGON2ID : Argon2id hashing algorithm

Example using options ( Optional )

salt : has to be minimum 22 char length. If not given then default salt will be used. Salt option is removed in PHP 7.0 so better not to use salt and allow PHP to use default salt.

cost : bcrypt cost is configurable and depends on the PHP version and hardware. PHP 8.4+ uses 12 as the default bcrypt cost.
$str="plus2net.com";
$options = array('cost' => 12);
$str_hash=password_hash($str,PASSWORD_DEFAULT,$options);
echo $str_hash;
Output will be a bcrypt hash whose salt is generated automatically by PHP.
Do not provide a manual salt. PHP generates a secure salt automatically. Explicit salt support is obsolete and is ignored by current PHP.
As seen from above we can use different algorithms with password_hash(), we can store the password in our database table with length 255 chars. Next we will learn how to match the stored password against user entered password by using password_verify()
String Functions password_verify(): To match the password with user entered password


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer