Hướng dẫn
Quảng cáo

Hàm sha1() trong PHP

Hướng dẫn cách sử dụng hàm sha1() trong lập trình PHP

Tác dụng của hàm sha1()

The sha1() function calculates the sha1 (Secure Hash Algorithm 1) hash of a string.

This function calculates the sha1 hash of string using the US Secure Hash Algorithm 1, and returns that hash. To calculate the sha1 hash of a file, use the sha1_file() function.

The following table summarizes the technical details of this function.

Return Value: Returns the sha1 hash on success, or FALSE on failure.
Version: PHP 4.3.0+

Warning: Using the sha1() function to secure passwords is not recommended, due to the fast nature of this hashing algorithm. Use the password_hash() function to hash passwords.


The basic syntax of the sha1() function is given with:

sha1(string, raw_format);

The following example shows the sha1() function in action.

// Sample string
$str = "Blackbird";

// Calculating the hash
echo sha1($str);


The sha1() function accepts the following parameters.

Parameter Description
string Required. Specifies the input string.
raw_format Optional. If set to true, it returns the hash in raw binary format with a length of 20. Default value is false which returns the hash as a 40-character hexadecimal number.

More Examples

Here're some more examples showing how sha1() function actually works:

The following example calculates the sha1 hash in different formats.

// Sample string
$str = "Blackbird";

// Calculating the hash
echo "SHA1 hash as a 40-character hexadecimal number: ".sha1($str)."<br>";
echo "SHA1 hash in 20-character raw binary format: ".sha1($str, TRUE);

The following example checks whether the two sha1 hashes are identical or not.

// Sample string
$str = "Blackbird";

// Test if two hashes are Identical
if(sha1($str) === "3d822d44b2c8f36565435a5134cf7aec391732fe"){
    echo "Blackbirds typically like to sing after rain.";

Bài viết này đã giúp ích cho bạn?

Bài viết mới