php

PHP SHA1() Function

PHP has many built-in functions to secure the data of the application. The hashing algorithm is one of the ways to secure the string data by creating a hash string of the string data. The SHA1() is a built-in function of PHP to create the hash string of any string value. The full form of SHA1 is Secure Hash Algorithm 1. It generates a hash string that is called a message digest. The different uses of this function are shown in this tutorial.

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

The first argument is mandatory and the hash string is generated based on the first argument value. The second argument is optional that contains a Boolean value. If the value of the second argument is TRUE, a hash string of 20 characters of data in binary format is generated. If the second argument is FALSE, a hash string of 40 characters in hex format is generated. It returns the hash value of the string that is used in the first argument of the function.

Different Examples of SHA1() Function

The different uses of the SHA1() function are shown in this part of the tutorial using multiple examples.

Example 1: Using SHA1() Function Without Optional Argument

Create a PHP file with the following script that creates 40 characters long hash value using the SHA1() function without the optional argument. The original string value and the generated hash value are printed later.

<?php
//Assign a string value
$strval = "Testing Message";
echo "The original string: $strval<br/>";
//Print the generated hash string
echo "The hash string : ".sha1($strval);
?>

Output:
The following output appears after executing the previous script:

Example 2: Using SHA1() Function With Optional Argument

Create a PHP file with the following script that creates the hash value using the SHA1() function with the optional argument. Forty (40) characters hash value are generated when False is used in the optional argument value of the SHA1() function. Twenty (20) characters hash value are generated when True is used in the optional argument value of the SHA1() function. The original string value, the generated hash value of 40 characters, and 20 characters are printed later.

<?php
//Assign a string value
$strval = "Testing Message";
echo "The original string: $strval<br/>";
//Print the generated hash string
echo "The hash string of 40 characters: ".sha1($strval, False)."<br/>";
//Print the generated hash string
echo "The hash string of 20 characters: ".sha1($strval, True)."<br/>";
?>

Output:
The following output appears after executing the previous script:

Example 3: Checking the Hash Value of the Particular String

Create a PHP file with the following script that checks if a hash value of a string is correct or incorrect. The string value is taken from the URL parameter and the hash value of that string value is compared with a particular hash value to confirm whether the taken string value is correct or not.

<?php
if (isset($_GET['msg']))
{
   //Generate the hash value of the string read from the URL
   $strval = sha1($_GET['msg']);
   //Print the original string value
   echo "The original string: ".$_GET['msg']."<br/>";
   //Check the hash value of the corresponding string value
   if ($strval == '640ab2bae07bedc4c163f679a746f7ab7fb5d1fa')
      echo "Correct hash value";
   else
      echo "Wrong hash value.";

}
else
   echo "String value is not given.";

?>

Output:
The following output appears after executing the previous script without the URL parameter:

The following output appears after executing the previous script by providing the valid string in the URL parameter:

Example 4: Using SHA1() Function for Validation

The SHA1() function can be used for validating the data. The way of validating the login information using the SHA1() function is shown in this tutorial. Create an HTML file named login.html with the following script that takes the username and password from the user using an HTML form. The form data is parsed using a PHP file named login.php.

login.html

<html>
<head>

<title> Login</title>
<style>

.input-format
{
    width: 80%;
    margin: 10px 0;
    padding: 15px 20px;  
    display: inline-block;
    box-sizing: border-box;
    border: 1px solid rgb(143, 197, 241);
}
</style>  
</head>
<body>
   <center> <h1>Login Form </h1> </center>
   <form action="login.php" method="post">
   <center>
   <div style="padding: 25px; background-color: rgb(152, 247, 242); width: 30%;" >
     <input class="input-format" type="text" placeholder="Username" name="un" required>
     <input class="input-format" type="password" placeholder="Password" name="pwd" required>
     <br/>
     <button type="submit" style="width: 40%; height: 10%; color: rgb(66, 16, 204); align-content: center;">Login</button>
  </div>  
  </center>
  </form>  
</body>
</html>

Create a PHP file named login.php with the following script. The username and password values that are submitted by the form are stored in two variables. Next, the value of the username and password are checked. If the username contains the “admin” value and the password contains the “secretpassword” value, the “Valid User” message is printed. Otherwise, the “Invalid User” message is printed.

login.php

<?php
//Check whether the variable is set or unset
if (isset($_POST['un']) && isset($_POST['pwd']))
{
  $username = $_POST['un'];
  $password = $_POST['pwd'];
  $hash_password = 'e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4';
  //Check whether the submitted value is empty or not
  if($username != "" && $password != "")
  {
     //Check whether the submitted values are valid or invalid
     if ($username == 'admin' && sha1($password) == $hash_password)
        echo "Valid User.";
     else
        echo "Invalid User.";
  }
  else
     echo "Username or password can't be empty.";

}

?>

Output:
The following output appears after executing the login.html from the browser:

Type the valid username and password in the login form and click on the Login button.

The following output appears for the valid username and password values:

The following output appears for the invalid username or password values:

Conclusion

The different uses of the SHA1() function are described in this tutorial using this function in multiple ways. PHP has many other functions like the SHA1() function to generate the hash values but this function is so simple to use for validating the data or checking the data integrity. We hope that this tutorial helps the PHP users to know how to use the SHA1() function properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.