PHP sha1() function

Example

Calculate the SHA-1 hash of the string "Hello":

<?php
$str = "Shanghai";
echo sha1($str);
?>

Run Instances

Definition and Usage

The sha1() function calculates the SHA-1 hash of a string.

The sha1() function uses the United States Secure Hash Algorithm 1.

Explanation from RFC 3174 - The United States Secure Hash Algorithm 1: SHA-1 generates a 160-bit output named message digest. The message digest can be input into a signature algorithm that can generate or verify message signatures. Signing the message digest instead of the message itself can improve process efficiency because the size of the message digest is usually much smaller than that of the message. The verifier of the digital signature must use the same hashing algorithm as the creator of the digital signature.

Tip:To calculate the SHA-1 hash of a file, use the sha1_file() function.

Syntax

sha1(string,raw)
Parameter Description
string Required. Specify the string to be calculated.
raw

Optional. Specify the hexadecimal or binary output format:

  • TRUE - Original 20-character binary format
  • FALSE - Default. 40-character hexadecimal number

Technical Details

Return Value: Returns the calculated SHA-1 hash if successful, or FALSE if failed.
PHP Version: 4.3.0+
Update Log: In PHP 5.0,raw Parameters become optional.

More Examples

Example 1

Output the result of sha1():

<?php
$str = "Shanghai";
echo "String: " . $str . "<br>";
echo "TRUE - Original 20-character binary format: " . sha1($str, TRUE) . "<br>";
echo "FALSE - 40-character hexadecimal number: " . sha1($str) . "<br>";
?>

Run Instances

Example 2

Output the result of sha1() and test it:

<?php
$str = "Shanghai";
echo sha1($str);
if (sha1($str) == "b99463d58a5c8372e6adbdca867428961641cb51")
  {
  echo "<br>I love Shanghai!";
  exit;
  }
?>

Run Instances