How to useHashing Functions in PHP
PHP has a few functions like md5(), sha1() and hash(), that can be used to hash a string based on certain algorithms like “sha1”, “sha256”, “md5” etc. All these function takes a string as an argument and output an Alpha-Numeric hashed string.
To learn more about these functions click here. Once we understand how we utilize these functions, our task becomes pretty simple.
- Generate a random number using rand() function.
- Hash it using one of the above functions.
Example 1:
<?php
$str=rand();
$result = md5($str);
echo $result;
?>
Output
7190bba9f6361764d423317d202402d5
Example 2:
<?php
$str=rand();
$result = sha1($str);
echo $result;
?>
Output
7898decff6889ba2521bb32259e571be9880da25
Example 3:
<?php
$str = rand();
$result = hash("sha256", $str);
echo $result;
?>
Output
690a4fea15d64168b512ad893f5e44bf13741a5c954f70fb6553e508965ad6f5
NOTE: All the above functions are hashing functions, hence the length of the string generated will always depend on the algorithm used, but for an algorithm it will always remain constant. So if you want to generate string of a fixed length, you can either truncate the generated string or concatenate with another string, based on the requirement.
Generating Random String Using PHP
Generate a random, unique, alpha-numeric string using PHP. Examples:
EA070
aBX32gTf
Table of Content
- Brute Force
- Using Hashing Functions
- Using uniqid() function
- Using random_bytes() function. (Cryptographically Secure)
- Using random_int() in a Custom Function
Contact Us