Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String sha1() Function



The PHP String sha1() function is used to cCalculate the sha1 hash of a string by using the "US Secure Hash Algorithm 1". It is not recommended to use this hashing algorithm to protect passwords due to its speed.

Syntax

Below is the syntax of the PHP String sha1() function −

string sha1 ( string $string, bool $binary = false )

Parameters

Here are the parameters of the sha1() function −

  • $string − It is the input string.

  • $binary − It is a boolean value that indicates the output. If it is set to true, the sha1 digest is returned in raw binary format with a length of 20; otherwise, the value is a 40-character hexadecimal.

Return Value

The sha1() function returns the sha1 hash as a string.

PHP Version

First introduced in core PHP 4.3.0, the sha1() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

Here is the basic example of the PHP String sha1() function to calculate the sha1 hash value of the given string.

<?php
   $string = "Hello World";
   $hash = sha1($string);

   echo "The SHA1 hash of '$string' is: $hash";
?>

Output

Here is the outcome of the following code −

The SHA1 hash of 'Hello World' is: 2ef7bde608ce5404e97d5f042f95f89f1c232871

Example 2

In the below PHP code we will try to use the sha1() function to verify the sha1 hash value of the given string.

<?php
   $str = 'pineapple';

   if (sha1($str) === 'ff9907a80070300578eb65a2137670009e8c17cf') {
      echo "Would you like a green or yellow pineapple?";
   }
?> 

Output

This will generate the below output −

Would you like a green or yellow pineapple?

Example 3

Now the below code calculates the SHA1 hash using the sha1() method and outputs it in raw binary format.

<?php
   $string = "PrivateData";
   $binaryHash = sha1($string, true);

   echo "The raw binary SHA1 hash of '$string' is: ";

   // Convert binary to hex for readable output
   echo bin2hex($binaryHash); 
?> 

Output

This will create the below output −

The raw binary SHA1 hash of 'PrivateData' is: 509554b9c372106e1610bad1fda4d725074078c9
php_function_reference.htm
Advertisements