i have a problem with generating a one time password that will expire once used or after a few miute.
this is what i want to do

page 1. create a captcha. if verification is valid then direct me to page2

page 2. this page asks for my name or user-id, my php will check if name or user_id exists, if it exists it will generate a 6-digit code and email or sms to the mobile number
or email associated with the name or user_id that was given and direct to page 3.
the generated code should expire after 10minutes or after it has been used.

page 3. now this page will ask me to enter code that was sent to me. if code i enter is correct then it will allow me to change/update my password . script should update password at the user-id or name that was given

everything works perferct, only thing not working is code generation and sms or emailing of the code

i dont know what to now or how or where. please dont worry about the site not being secure or saving password

without encryption.
here is what i did so far

index.php

    <?php session_start();

    if(isset($_POST['Submit'])){
        // code for check server side validation
        if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){  
            $msg="<span style='color:red'>The Validation code does not match!</span>";// Captcha verification is incorrect.       
        }else{// Captcha verification is Correct. Final Code Execute here!      
            $msg="<span style='color:green'>The Validation code has been matched.</span>";    

            header("Location: userid.php"); 
        }
    }   
    ?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>verification</title>
    <link href="./css/style.css" rel="stylesheet">
    <script type='text/javascript'>
    function refreshCaptcha(){
        var img = document.images['captchaimg'];
        img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
    }
    </script>
    </head>
    <body>


    <form action="" method="post" name="form1" id="form1" >
      <table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="table">
        <?php if(isset($msg)){?>
        <tr>
          <td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
        </tr>
        <?php } ?>
        <tr>
          <td align="right" valign="top"> Validation code:</td>
          <td><img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'><br>
            <label for='message'>Enter the code above here :</label>
            <br>
            <input id="captcha_code" name="captcha_code" autofocus type="text">
            <br>
            Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.</td>
        </tr>
        <tr>
          <td> </td>
          <td><input name="Submit" type="submit" onclick="return validate();" value="Submit" class="button1"></td>
        </tr>
      </table>
    </form>
    </body>
    </html>

userid.php


    <?php
    session_start();
     require_once('mySQLConnect.php');
     $error='';
     $number='';
     if  (isset($_REQUEST['submit'])){
            $user_id=$_REQUEST['user_id'];
             $sql="SELECT * FROM members WHERE  user_id= '$user_id'";
               mysqli_query($conn,$sql);
               $result=mysqli_query($conn,$sql);
               $count=mysqli_num_rows($result);

       if($count=='1'){
             $sql2="SELECT phone FROM members where user_id= '$user_id'";
           $result2=mysqli_query($conn,$sql2);


    $row=mysqli_fetch_assoc($result2);
    $number=$row["phone"];
    header("Location: confirm.php?number=$number");

    mysqli_free_result($result2);

           } 
                 else{
                        $error="USER_ID INCORRECT OR DOES NOT EXIST!<br>";
                    }
               }
    ?>


    <html> 
    <head>
    <title>reset</title>


    <style>
    h1 {
    color:#0C0; 
    }
    .loadinggif 
    {
       background:
         url('img/spinner.gif')
         no-repeat
         right center;
    }
    span {
            color:#C00;
            font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
            }
    </style>
    </head>
    <body>
    <center>

                    <form method="post" name="form1" id="form1">
                    <br><br>

        <h1>enter your user-id to continue</h1>

        <label for="test">user-id:</label>
            <input type="text" name="user_id" id="user_id" autofocus required 
             placeholder="user-id"  maxlength="7" ><br><br>

       <span><?php echo   $error ?></span><br>
            <input type="submit" value="submit" name="submit" id="submit">

                    </form>
      </center>               
    </body>
    </html>

confirm.php


    <?php
    session_start();

    require_once('mySQLConnect.php');
     if (isset($_REQUEST['number'])) {
        $number=$_REQUEST["number"];
    }
    ?>
    <html>
    <head>
    <title>confirm</title>
    </head>
    <style>
    h1 {
    color:#F93;
    font-size:19px; 
    }
    h2 {
    color:#F00;
    font-size:17px; 
    }
    </style>
    <body>
    <center><br><br>
    <form name="form1" method="post">
    <h1>sms was sent to </h1><h2> <?php echo $number ?></h2>
     <h1>please enter it below</h1>
    <input type="text" name="code" id="code"><br><br>
    <input type="submit" name="submit" value="submit">
    </form>
    </center>
    </body>
    </html>
oh sorry here is other info to make it easy for you guys to text.
it includes my database and captcha info 


captcha.php

<?php
    session_start();
    include("phptextClass.php");    

    /*create class object*/
    $phptextObj = new phptextClass();   
    /*phptext function to genrate image with text*/
    $phptextObj->phpcaptcha('#162453','#fff',120,40,10,25); 
 ?>

phptextClass.php

<?php

class phptextClass
{   
    public function phptext($text,$textColor,$backgroundColor='',$fontSize,$imgWidth,$imgHeight,$dir,$fileName)
    {
        /* settings */
        $font = './calibri.ttf';/*define font*/
        $textColor=$this->hexToRGB($textColor); 

        $im = imagecreatetruecolor($imgWidth, $imgHeight);  
        $textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);  

        if($backgroundColor==''){/*select random color*/
            $colorCode=array('#56aad8', '#61c4a8', '#d3ab92');
            $backgroundColor = $this->hexToRGB($colorCode[rand(0, count($colorCode)-1)]);
            $backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
        }else{/*select background color as provided*/
            $backgroundColor = $this->hexToRGB($backgroundColor);
            $backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
        }

        imagefill($im,0,0,$backgroundColor);    
        list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize); 
        imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
        if(imagejpeg($im,$dir.$fileName,90)){/*save image as JPG*/
            return json_encode(array('status'=>TRUE,'image'=>$dir.$fileName));
        imagedestroy($im);  
        }
    }   

    public function phpcaptcha($textColor,$backgroundColor,$imgWidth,$imgHeight,$noiceLines=0,$noiceDots=0,$noiceColor='#162453')
    {   
        /* Settings */
        $text=$this->random();
        $font = './font/monofont.ttf';/* font */
        $textColor=$this->hexToRGB($textColor); 
        $fontSize = $imgHeight * 0.75;

        $im = imagecreatetruecolor($imgWidth, $imgHeight);  
        $textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);          

        $backgroundColor = $this->hexToRGB($backgroundColor);
        $backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);

        /* generating lines randomly in background of image */
        if($noiceLines>0){
        $noiceColor=$this->hexToRGB($noiceColor);   
        $noiceColor = imagecolorallocate($im, $noiceColor['r'],$noiceColor['g'],$noiceColor['b']);
        for( $i=0; $i<$noiceLines; $i++ ) {              
            imageline($im, mt_rand(0,$imgWidth), mt_rand(0,$imgHeight),
            mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), $noiceColor);
        }}              

        if($noiceDots>0){/* generating the dots randomly in background */
        for( $i=0; $i<$noiceDots; $i++ ) {
            imagefilledellipse($im, mt_rand(0,$imgWidth),
            mt_rand(0,$imgHeight), 3, 3, $textColor);
        }}      

        imagefill($im,0,0,$backgroundColor);    
        list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize); 
        imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);      

        imagejpeg($im,NULL,90);/* Showing image */
        header('Content-Type: image/jpeg');/* defining the image type to be shown in browser widow */
        imagedestroy($im);/* Destroying image instance */
        if(isset($_SESSION)){
            $_SESSION['captcha_code'] = $text;/* set random text in session for captcha validation*/
        }
    }

    /*for random string*/
    protected function random($characters=6,$letters = '23456789bcdfghjkmnpqrstvwxyz'){
        $str='';
        for ($i=0; $i<$characters; $i++) { 
            $str .= substr($letters, mt_rand(0, strlen($letters)-1), 1);
        }
        return $str;
    }   

    /*function to convert hex value to rgb array*/
    protected function hexToRGB($colour)
    {
            if ( $colour[0] == '#' ) {
                    $colour = substr( $colour, 1 );
            }
            if ( strlen( $colour ) == 6 ) {
                    list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
            } elseif ( strlen( $colour ) == 3 ) {
                    list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
            } else {
                    return false;
            }
            $r = hexdec( $r );
            $g = hexdec( $g );
            $b = hexdec( $b );
            return array( 'r' => $r, 'g' => $g, 'b' => $b );
    }       

    /*function to get center position on image*/
    protected function ImageTTFCenter($image, $text, $font, $size, $angle = 8) 
    {
        $xi = imagesx($image);
        $yi = imagesy($image);
        $box = imagettfbbox($size, $angle, $font, $text);
        $xr = abs(max($box[2], $box[4]));
        $yr = abs(max($box[5], $box[7]));
        $x = intval(($xi - $xr) / 2);
        $y = intval(($yi + $yr) / 2);
        return array($x, $y);   
    }
}
?>

mySQLConnect.php

<?php
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $database = 'reg';
    $conn     = mysqli_connect($dbhost,$dbuser,$dbpass,$database) or die("Error " . mysqli_error($link));   


?>

members.sql

-- phpMyAdmin SQL Dump
-- version 4.1.6
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 28, 2015 at 03:27 PM
-- Server version: 5.6.16
-- PHP Version: 5.5.9

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `faizel`
--

-- --------------------------------------------------------

--
-- Table structure for table `members`
--

CREATE TABLE IF NOT EXISTS `members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(7) NOT NULL,
  `phone` varchar(10) NOT NULL,
  `oneTime` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `members`
--

INSERT INTO `members` (`id`, `user_id`, `phone`, `oneTime`, `name`) VALUES
(1, '123456', '0824548961', '', 'derick'),
(2, '246810', '0835849888', '', 'peter'),
(3, '3691215', '078088888', '', 'daddy');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Where's your code for sending the email? Do you have an email server setup yet?

Generating a 6 digit pin is as simple as:
$pin = rand(100000,999999);

Store the pin and associated user id into a table. When the user enters the pin, check it with the table that the username and pin match up. If so, clear the entry from the table and let the user type a new password.

thanx alot. i generated the pin, what i did was

function generateRandomString($length = 6) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

 $code=generateRandomString();

so that did my pin. and as soon as it was created it was saved in my database.
and follwed by a page where code is requeted to cintinue. as as the user inserts the code, the page redirects to "new password" and updates the code to null in the database. this helps user not to re-use the code again. my new password page logs out if inactive. to be honest. i can send the email usiing phpmailer but what i want is to use sms service. any ideas?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.