How to Create One Time Password (OTP) in PHP

A One Time Password (OTP) is a very popular way to use online transactions. It is used for real-time banking and monetary transactions. The following procedure is used by the OTP:

  1. Check email, phone number and user ID.
  2. You can change or reset user profile information.
  3. Real-time transaction authentication.
  4. Check the validation of the email and mobile number.

Create a One Time Password (OTP) in PHP

  1. Step 1

    Create the file otppass.php with the following code:
    1. <?php   
    2.    /**** ANANT ONE-TIME PASSWORD EXAMPLE ****/  
    3.   
    4.    session_start(); //STARTING THE SESSION AND THE   
    5.   
    6.    session_set_cookie_params(360);//SESSION EXPIRES IN 6 MINUTES   
    7.   
    8.    // USERNAME AND PASSWORD ARRAYS   
    9.   
    10.    $user = array(  
    11.    'user1' => annat,  
    12.    'scott' => tiger,  
    13.    ‘anat’ => xxxxxxx,  
    14.    );  
    15.   
    16.    $phone = array(  
    17.    'user1' => '+5353535333,  
    18.    'scott' => '+44243535353,  
    19.    anat’ => '+23554444444,  
    20.    );  
    21.   
    22.    // Login information for anant NG - SMS Gateway  
    23.    $anant_user = "admin";  
    24.    $anant_password = "abc123";  
    25.    $anant_url = "http://127.0.0.1:9501/api?";  
    26.   
    27.   
    28.    // Functions used to send the SMS message   
    29.    function httpRequest($url){  
    30.       $pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";  
    31.       preg_match($pattern,$url,$args);  
    32.       $in = "";  
    33.       $fp = fsockopen("$args[1]"$args[2], $errno$errstr, 30);  
    34.       if (!$fp) {  
    35.          return("$errstr ($errno)");  
    36.          } else {  
    37.                   $out = "GET /$args[3] HTTP/1.1\r\n";  
    38.                   $out .= "Host: $args[1]:$args[2]\r\n";  
    39.                   $out .= "User-agent: anant PHP client\r\n";  
    40.                   $out .= "Accept: */*\r\n";  
    41.                   $out .= "Connection: Close\r\n\r\n";  
    42.   
    43.                   fwrite($fp$out);  
    44.                   while (!feof($fp)) {  
    45.                   $in.=fgets($fp, 128);  
    46.                   }  
    47.                }  
    48.                fclose($fp);  
    49.                return($in);  
    50.             }  
    51.   
    52.             function anantSend($phone$msg$debug=false){  
    53.             global $anant_user,$anant_password,$anant_url;  
    54.             $url = 'username='.$anant_user;  
    55.             $url.= '&password='.$anant_password;  
    56.             $url.= '&action=sendmessage';  
    57.             $url.= '&messagetype=SMS:TEXT';  
    58.             $url.= '&recipient='.urlencode($phone);  
    59.             $url.= '&messagedata='.urlencode($msg);  
    60.   
    61.             $urltouse = $anant_url.$url;  
    62.             //if ($debug) { echo "Request: <br>$urltouse<br><br>"; }  
    63.   
    64.             //Open the URL to send the message  
    65.             $response = httpRequest($urltouse);  
    66.             if ($debug) {  
    67.                echo "Response: <br><pre>".  
    68.                str_replace(array("<",">"),array("<",">"),$response).  
    69.                "</pre><br>"; }  
    70.             return($response);  
    71.          }  
    72.   
    73.   
    74.       //FUNCTION TO GENERATE ONE-TIME PASSWORD   
    75.       function anantOTP($length = 8, $chars = 'abcdefghijklmnopqrstuvwxyz1234567890')  
    76.       {  
    77.          $chars_length = (strlen($chars) - 1);  
    78.          $string = $chars{rand(0, $chars_length)};  
    79.          for ($i = 1; $i < $length$i = strlen($string))  
    80.          {  
    81.             $r = $chars{rand(0, $chars_length)};  
    82.             if ($r != $string{$i - 1}) $string .= $r;  
    83.          }  
    84.          return $string;}  
    85.   
    86.   
    87.          //IF DEBUG VARIABLE IS TRUE, THE RESPONSE OF THE HTTP REQUEST WILL BE WRITTEN TO THE SCREEN   
    88.          $debug = false;  
    89.   
    90.          // IF NOT POSTED ANYTHING YET, THE LOGIN PAGE IS LOADING   
    91. if (emptyempty($_POST)){  
    92.       $i=0;  
    93.       echo('   
    94.    <html>  
    95.       <body>  
    96.       <h1>One Time Password Form</h1>  
    97.       <form method="POST">  
    98.       <table border=1>  
    99.          <tr>  
    100.             <td>Username:</td>  
    101.             <td><input type="text" name="username"></td>  
    102.          </tr>  
    103.          <tr>  
    104.             <td>Password</td>  
    105.             <td><input type="password" name="password"></textarea></td>  
    106.          </tr>  
    107.          <tr>  
    108.             <td> </td>  
    109.             <td><input type=submit name=submit value="Get Otp" OnClick="anantSend(this.form);"></td>  
    110.          </tr>  
    111.       </table>  
    112.    </form>  
    113.    </body>  
    114. </html>');}  
    115.   
    116. //IF OTP HAS POSTED YET, anantOTP FUNCTION WILL GENERATE ONE   
    117. if (emptyempty($_POST['otphtml'])){  
    118. $_SESSION['otp']=anantOTP();  
    119.   
    120.   
    121. // CHECKING USER CREDENTIALS   
    122. if ($password!=$user[$username] || ((emptyempty($_POST['username']) && (!emptyempty($_POST['password'])))) || (emptyempty($_POST['password']) && (!emptyempty($_POST['username']))))  
    123. echo ('Please enter a valid username or password!');  
    124. elseif ((!emptyempty($_POST['submit'])) && (emptyempty($_POST['password'])) && (emptyempty($_POST['username'])))   
    125. echo ('No username or password entered');  
    126.   
    127. elseif($password=$user[$username]){  
    128.   
    129.    //SENDING THE PASSWORD AND LOADING THE OTP-VERIFYING PAGE   
    130.    anantSend($phone[$_POST['username']],'Dear '.$username.'! Your One-Time password is: '.$_SESSION['otp'],$debug);  
    131.    echo (' <html>  
    132.    <body>  
    133.       <h1>Please enter your One-Time password to enter the site!</h1>  
    134.          <form method="POST">  
    135.             <table border=1>  
    136.                <tr>  
    137.                <td>Your One-time password:</td>  
    138.                <td><input type="text" name="otphtml"></td>  
    139.                </tr>  
    140.                <tr>  
    141.                <td> </td>  
    142.                <td><input type=submit name=submit value="Confirm OTP"></td>  
    143.                </tr>  
    144.             </table>  
    145.          </form>  
    146.       </body>  
    147.    </html>');  
    148. }}  
    149. else{   
    150.   
    151.    //IF AN OTP HAS ALREADY SENT, CHECKING ITS VALIDITY AND REDIRECTING TO THE PROTECTED CONTENT   
    152.    $otp1=$_POST['otphtml'];   
    153.    include('protectedcontent.php');}  
    154.   
    155. ?>  
  2. Step 2

    Create another file protectedcontent.php.
    1. <?php  
    2.   
    3. if ($_SESSION['otp']==$otp1){  
    4.    echo('<html>  
    5.    <body><h2>You\'ve been successfully verified your One-Time Password</h2></body>  
    6.    </html>');}  
    7.   
    8.    else { echo('<html>  
    9.       <body><h2>Wrong Password!</h2></body>  
    10.    </html>');}  
    11.   
    12. ?>  


Similar Articles