PHP - hash() Function
Definition and Usage
The hash() function returns a hash value for the given data based on the algorithm like (md5, sha256). The return value is a string with hexits (hexadecimal values).
Syntax
hash ( string $algo , string $data [, bool $raw_output = FALSE ] ) : string
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
algo Name of the hashing algorithm. There is a big list of algorithm available with hash, some important ones are md5, sha256, etc. |
| 2 |
data The data you want the hash to be generated. Please note once the hash is generated it cannot be reversed. |
| 3 |
raw_output By default, the value is false and hence it returns lowercase hexits values. If the value is true, it will return raw binary data. |
Return Values
PHP hash() function returns a string with lowercase hexits. If the raw_output is set to true, it will return raw binary data.
PHP Version
This function will work from PHP Version greater than 5.1.2.
Example 1
To generate hash value using md5 Algorithm −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint');
?>
Output
This will produce the following result −
The hash of Welcome to Tutorialspoint is - 8ab923b97822bd258bf882e41de6ebff
Example 2
To generate hash value using sha256 Algorithm −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('sha256', 'Welcome to Tutorialspoint');
?>
Output
This will produce the following result −
The hash of Welcome to Tutorialspoint is - a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e
Example 3
To generate hash using crc32b Algorithm −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('crc32b', 'Welcome to Tutorialspoint');
?>
Output
This will produce the following result −
The hash of Welcome to Tutorialspoint is - cd12151c
Example 4
To generate hash with raw_output as true −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint', true);
?>
Output
This will produce the following result −
The hash of Welcome to Tutorialspoint is - #x"%