PHP sha1 is an inbuilt function in PHP. It returns the SHA-1 Hash of the string after hashing it with the US Secure Hashing Algorithm 1. Hashing a string is very important to store critical data in a database like for storing user’s passwords. In this article, we will discuss the PHP sha1 Function. Also, we will discuss a couple of examples of using it.
WARNING: It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices.https://php.net/manual/en/function.sha1.php
string sha1($string, $getRawOutput = false)
The function expects two parameters. However, only one parameter is mandatory while the other is optional.
- $string: The string which needs to be hashed is the first parameter. Also, it is a mandatory parameter.
- $getRawOutput: The second parameter is a boolean value with default as false. By default the function returns a 40 character lowercase hex character sequence. However, on passing true to the function, it returns a raw binary string of length 20.
The PHP sha1 Function returns string after hashing it using the US Secure Hash Algorithm 1. By default, the function returns the string as a 40 character lowercase hex character sequence. It can also return a string raw binary string of 20 characters.
Let’s discuss a few examples of using the function.
Example 1: 40 Character Hex Character Sequence
For instance, consider an example of the function returning a 40 character hex character sequence.
<?php $string = 'Concatly'; $hashedString = sha1($string); echo $hashedString; ?>
In the above example, the function returns the sha1 hash of the string as follows:
Example 2: 20 Character Raw Binary
Also, on passing the second parameter as true, the function will return a 20 character raw binary string.
<?php $string = 'Concatly'; $hashedString = sha1($string, true); echo $hashedString; ?>
OUTPUT: !>G_�@���df+ �i�5
Uses of PHP sha1 Function
The authentication system is one of the most crucial components of a website. It is very important to remove vulnerabilities which an attacker may exploit. One such vulnerability is storing the user’s password in plain text form. If an unauthorized person gains access to the database, the whole system will get compromised.
Password hashing is a method in which the user’s password is hashed to a fixed length and stored in the database in an encrypted form. Even if someone gets to know the hashed password, he cannot compromise the whole system. PHP sha1 is one of the function which is helpful for the same.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.