PHP hash Function | Generate a Hash Value

PHP hash is an inbuilt function in PHP. It generates a hash value of the input string using the algorithm of your choice. In this article, we will discuss the PHP hash Function. Also, we will discuss a few examples of using it.

Syntax

string hash($algo, $string, $getRawOutput = false)

Parameters

The function expects three parameters. However, two parameters are mandatory and one is optional. The description of the parameters is as follows:

  • $algo: The first parameter refers to the hashing algorithm to use. Some commonly used algorithms are sha1, sha256, md5, etc.
  • $string: The string which needs to be hashed is the second parameter. Also, it is a mandatory parameter.
  • $getRawOutput: The third parameter is a boolean value with default as false. If true, the function returns the hash in raw binary format.

Return Value

The function returns the hash string either in lowercase hexadecimal characters or raw binary format as per the third parameter.

Examples

Let’s discuss a few examples of using the function.

Example 1: Generating sha1 Hash

<?php
	
	$string = 'Concatly';
	$hashedString = hash('sha1', $string);
	echo $hashedString;

?>
OUTPUT:
213e475fac4083afcf64662b160d09f069f91a35

Also, you can use the PHP sha1 Function to generate sha1 hash.

Example 2: Generating md5 Hash

Similarly, you can generate md5 hash using this function

<?php
	
	$string = 'Concatly';
	$hashedString = hash('md5', $string);
	echo $hashedString;

?>
OUTPUT:
17ea06a7183ebe0415f780e70013bcc4

Also, you can use the PHP md5 Function to generate md5 hash.

Example 3: Raw Binary Format

By passing the third parameter as true, you can get the return hash in raw binary format.

<?php
	
	$string = 'Concatly';
	$hashedString = hash('md5', $string, true);
	echo $hashedString;

?>

Conclusion

In conclusion, we discussed the PHP hash Function. You can read more about it on the Official PHP Documentation. Additionally, you can learn about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *