• PHP Video Tutorials

PHP - Hash init() Function



Definition and Usage

The hash_init() function initializes an incremental hashcontext that can be used with other hash functions like hash_update(), hash_final() etc. It takes input as a hash algorithm and the output as a hash context.

A hashContext is generated based on the hash_algo used inside the hash_init(). You can update your data or message with the hashcontext using hash_update() function and get the final hash using hash_final().

Syntax

hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] ) : HashContext

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.

To get the full list of algorithms supported use the hashing function hash_algos()

2

options

There is only one option supported and that is HASH_HMAC. If you are using options, the key is also mandatory.

3

key

If HASH_HMAC is used as an option, the key also has to be given and it will be a shared secret key that will be used with HMAC hashing method.

Return Values

PHP hash_init() function returns a hashing context. The hashing context can be used with other hash function like hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

PHP Version

This function will work from PHP Version greater than 5.1.2.

Example 1

To generate hashing context −

<?php
   $hash_context = hash_init('md5');
   hash_update($hash_context, 'Testing php');
   hash_update($hash_context, ' hash functions.');
   echo hash_final($hash_context);
?>

Output

This will produce the following result −

e4310012c89a4b8479fd83694a2a3a31

Example 2

Using hash_init() with hash_copy() −

<?php
   $hash_context = hash_init("md5");
   hash_update($hash_context, "Welcome To Tutorialspoint");
   $hash_copy= hash_copy($hash_context);
   echo hash_final($hash_context);
   echo "<br/>";
   hash_update($hash_copy,  "Welcome To Tutorialspoint");
   echo hash_final($hash_copy);
?>

This will produce the following result −

6211420491a571f89f970683221d4480<br/>d0b25da996bf035057aba79082c53b30
php_function_reference.htm
Advertisements