Generating OTP (One time Password) in PHP
Now these days, OTP (one time password) is mandatory in almost each and every service. A developer can generate OTP in many ways but the challenge is not to be predictive as any one can predict the OTP and can exploit the service.
Some of popular format of OTPs are:
- 4 or 6 digit Numeric OTP.
- 4 or 6 alphabetic (lowercase / uppercase) OTP.
- 4 or 6 digit alphanumeric OTP.
Examples for n-digit numeric OTP:
Input : n = 4
Output : 8723
Input : n = 8
Output : 23914072
Note: The output of program will be different in every execution.
One of the best way to generate OTP is to use random function. But using random function directly can be dangerous. So here is an method which uses random function and some algorithm for generating the n-digit numeric OTP.
Program:
<?php
function generateNumericOTP( $n ) {
$generator = "1357902468" ;
$result = "" ;
for ( $i = 1; $i <= $n ; $i ++) {
$result .= substr ( $generator , (rand()%( strlen ( $generator ))), 1);
}
return $result ;
}
$n = 6;
print_r(generateNumericOTP( $n ));
?>
|
Last Updated :
10 Oct, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...