- PHP

How to hash a string in PHP

Sensitive data, such as user passwords, should be stored in the database as hashes.

In PHP we have a few functions that allow us to make a hash from our string.

The function I recommend is password_hash. It allows us to specify the algorithms we want to use for hashing. In most cases, the best choice should be PASSWORD_DEFAULT.

Example:

Hash password with default method at the time. In PHP 8 it’s bcrypt algorithm.

<?php

echo password_hash('hello123', PASSWORD_DEFAULT);

?>

Alternatively, you can use hash() function. It offers hashing in algorithms such as md5, sha1, sha256, haval160,4, and more. Just specify the method in the first function argument.

Example:

Hash the password with MD5 in PHP.

<?php

echo hash('md5', 'hello123');

?>