How to Make OTP (One Time Password) System Using Php

Create OTP System In PHP with Simple Mobile SMS Integration: Today I am here to introduce you to OTP system and how to make OTP (One Time Password) system using php. OTP is the need of today’s website and mobile apps. Everyone seller or website owner want valid customer on their platform. So As i am a web developer and today our every clients are searching for an otp system, it might be an Email Based OTP System or Mobile Based OTP System. So first here i wanna let you know about OTP System.

Create Secure OTP System using PHP

After a discussion on social media with some experts, I decided to share this with you, Creating OTP System In PHP for production or a live website is really tough for beginner need some Crypto expert which can make it easily. Here I am providing you a basic code for php otp system which you can use for small tasks on your website. Here i am sharing Why Security Is Important in OTP System, So for secure OTP System you need a cryptographically secured random number however in this post the openssl_random_pseudo_bytes() is a way which can make a secured random number and i tried my best to share a secured code with you. I also using CryptoLib Which can help to make more secure random number. I will recommend you to use Google Authenticator to create best OTP System. Now Here in this post i will share how to integrate Google Authenticator for OTP system PHP.

How to Make OTP System in Php
Make OTP System in Php

[BUTTON url=”http://www.infotheme.in/blog/demo/php/otp-system-using-php/”]See Live Demo[/BUTTON]

[BUTTON url=”http://www.infotheme.in/blog/wp-content/uploads/2016/08/otp-system-using-php.zip”]Download Now[/BUTTON]

What is OTP (One Time Password) System – Create OTP System In PHP:

A OTP or One Time Password System is a concept to prevent spam and Unwanted hack on website and Mobile App. It helps individual users to make secured their data online on any OTP integrated website. ONE TIME PASSWORD is an automatically generated numeric or alphanumeric strings which helps in authentication of a single transaction or session of particular user. The number changes in a timely manner, depending on how it is configured in coding / Program.

Also Learn : How to install LAMPP and WordPress in Digital Ocean with Ubuntu

How OTP System Works:

OTP always works according it’s program or coding. It depends on website requirement and how that website want to integrate it to authenticate sessions or transactions of their users. It can be used in Registration or Login system of Customer Panel. Most of popular website using OTP system for Login and Registration of User / Customers. And Many other websites are using OTP for payment transactions and other important or confidentials sessions, which helps them to prevent user sessions with unwanted hacks.

How to Create OTP System In PHP

So it’s time to create one time password for your website, I know you want to make a secured session for your users or customers, Oh’O please wait before creating a OTP System using PHP, i want to tell you about Mobile and Email Based OTP system.

What Is Mobile Based OTP System :

When we use a Mobile SMS gateway to authenticates users or send One Time Password to Users via TEXT SMS on their mobile. It called Mobile based OTP System. For Mobile based OTP system you have to Buy Bulk SMS Service from SMS Service Provider. Which will cost you an amount, so this is li’l bit costly for startups.

What Is Email Based OTP system: 

Email is best way to send any information, but in case of OTP i will recommend you to use Mobile Based or SMS based OTP System. But if you don’t have a budget to buy a BULK SMS Service, so you can send your otp via Email to your users for authentication of any session or transaction.

Now here i will tell you about Configuration of OTP system using PHP and SMS gateway Integration for OTP System.

How to Generate OTP Code Using PHP

Here i am writing a code so you can generate a unique code as otp for users and customers (One Time Password), So let’s focus on “how to generate one time password (otp code)”:

$otp_code = strtoupper(bin2hex(openssl_random_pseudo_bytes(3))); // A smart code to generate OTP PIN.

In this sample of code we will generate a 6 Character Alphanumerical digit / character.

How to Create OTP Code By Secured PHP Library | Generate OTP Number in Php

So guys after a long time i came to meet you here today, Do you know why ? because I was busy in a long holidays for my honeymoon. Hmm! do you think a programmer can go for a long vacation 🙁 No guys is just a myth, we are programmers and we will die after submitting a project to client without any errors and 1k+ re-checks. So i think i don’t have words now regarding my awesome holiday which i spent with my wife ( Yes it’s my laptop 🙂 ).

So let’s start  with code so guys few days ago I was working with a new cms which  i developed for my future presentation in Industry. So I found a php library which can be used to generate some random cryptographically secured strings. Now here the name of my new announcement is “RandomLib (A Secure PHP library to make otp system or some random secured string in php)“. I think you have great knowledge of composer, hmm! what is this man ? 😯 You really don’t know ? No man i am newbie Okay okay i thought an expert of Laravel is there. Okay no problem simply a composer is used to integrate libraries or modules or extensions into projects.

So here you have to follow these few commands to get rid from an unsecured otp code.

$ composer require ircmaxell/random-lib

A factory is used to get generators of varying strength:

$factory = new RandomLib\Factory;

$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM)); // This is the magic method of Factory to generate random string

If you want a limitation in otp code just use it

$generator->generateString(8, 'abcdef');

If you fill there is a problem in implementation of this library just comment down or ask to father of library Check Git Here

This Is A New Updates for my happy lovers 😉

What is OTP Confirmation and Why OTP Verification Required:

So here is a question in my mind why OTP Verification is required, so after sending an OTP to user’s mobile number or email, you need to confirm user’s otp code. So you can save otp code to a table as a temporary value in database. And when user will input otp code, just try to confirm the orp code using mysql query. Instead of session you should verify user code from database’s data.

So here is the code to confirm otp using temporary data in database:

$dbLink = new PDO('mysql:host=localhost;dbname=yourdbname', "dbusername", "dbuserpassword");

$statement = $dbLink->prepare("SELECT n_otp_email from n_otp_table where n_otp_email = :otp_email and n_otp_code = :otp_code");
$statement->execute(array(
"otp_email" => "$re_email",
"otp_code" => "$re_otp_code"
));
$fetch = $statement->fetch();
if($fetch[0]){
$msg ="Thanks To Verify Your OTP Code!";

}

Integrate Google Authenticator Using PHP – Google TOTP 2FA

In this part of post we will learn How to implement / integrate Google TOTP 2FA to make secure your OTP system. Google Authenticator is a (TOTP) Time Based One Time Password, It’s initialize with RFC 4648 encoded seed value. Now here is a library which was developed by phill and i wanna share it with you.

So here is step by step guide for GOOGLE TOTP 2FA Implementation :

Create A file with name Google2FAClass.php

class Google2FA {

	const keyRegeneration 	= 30;	// Interval between key regeneration
	const otpLength		= 6;	// Length of the Token generated

	private static $lut = array(	// Lookup needed for Base32 encoding
		"A" => 0,	"B" => 1,
		"C" => 2,	"D" => 3,
		"E" => 4,	"F" => 5,
		"G" => 6,	"H" => 7,
		"I" => 8,	"J" => 9,
		"K" => 10,	"L" => 11,
		"M" => 12,	"N" => 13,
		"O" => 14,	"P" => 15,
		"Q" => 16,	"R" => 17,
		"S" => 18,	"T" => 19,
		"U" => 20,	"V" => 21,
		"W" => 22,	"X" => 23,
		"Y" => 24,	"Z" => 25,
		"2" => 26,	"3" => 27,
		"4" => 28,	"5" => 29,
		"6" => 30,	"7" => 31
	);

	/**
	 * Generates a 16 digit secret key in base32 format
	 * @return string
	 **/
	public static function generate_secret_key($length = 16) {
		$b32 	= "234567QWERTYUIOPASDFGHJKLZXCVBNM";
		$s 	= "";

		for ($i = 0; $i < $length; $i++)
			$s .= $b32[rand(0,31)];

		return $s;
	}

	/**
	 * Returns the current Unix Timestamp devided by the keyRegeneration
	 * period.
	 * @return integer
	 **/
	public static function get_timestamp() {
		return floor(microtime(true)/self::keyRegeneration);
	}

	/**
	 * Decodes a base32 string into a binary string.
	 **/
	public static function base32_decode($b32) {

		$b32 	= strtoupper($b32);

		if (!preg_match('/^[ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]+$/', $b32, $match))
			throw new Exception('Invalid characters in the base32 string.');

		$l 	= strlen($b32);
		$n	= 0;
		$j	= 0;
		$binary = "";

		for ($i = 0; $i < $l; $i++) {

			$n = $n << 5; // Move buffer left by 5 to make room $n = $n + self::$lut[$b32[$i]]; // Add value into buffer $j = $j + 5; // Keep track of number of bits in buffer if ($j >= 8) {
				$j = $j - 8;
				$binary .= chr(($n & (0xFF << $j)) >> $j);
			}
		}

		return $binary;
	}

	/**
	 * Takes the secret key and the timestamp and returns the one time
	 * password.
	 *
	 * @param binary $key - Secret key in binary form.
	 * @param integer $counter - Timestamp as returned by get_timestamp.
	 * @return string
	 **/
	public static function oath_hotp($key, $counter)
	{
	    if (strlen($key) < 8)
		throw new Exception('Secret key is too short. Must be at least 16 base 32 characters');

	    $bin_counter = pack('N*', 0) . pack('N*', $counter);		// Counter must be 64-bit int
	    $hash 	 = hash_hmac ('sha1', $bin_counter, $key, true);

	    return str_pad(self::oath_truncate($hash), self::otpLength, '0', STR_PAD_LEFT);
	}

	/**
	 * Verifys a user inputted key against the current timestamp. Checks $window
	 * keys either side of the timestamp.
	 *
	 * @param string $b32seed
	 * @param string $key - User specified key
	 * @param integer $window
	 * @param boolean $useTimeStamp
	 * @return boolean
	 **/
	public static function verify_key($b32seed, $key, $window = 4, $useTimeStamp = true) {

		$timeStamp = self::get_timestamp();

		if ($useTimeStamp !== true) $timeStamp = (int)$useTimeStamp;

		$binarySeed = self::base32_decode($b32seed);

		for ($ts = $timeStamp - $window; $ts <= $timeStamp + $window; $ts++)
			if (self::oath_hotp($binarySeed, $ts) == $key)
				return true;

		return false;

	}

	/**
	 * Extracts the OTP from the SHA1 hash.
	 * @param binary $hash
	 * @return integer
	 **/
	public static function oath_truncate($hash)
	{
	    $offset = ord($hash[19]) & 0xf;

	    return (
	        ((ord($hash[$offset+0]) & 0x7f) << 24 ) |
	        ((ord($hash[$offset+1]) & 0xff) << 16 ) |
	        ((ord($hash[$offset+2]) & 0xff) << 8 ) |
	        (ord($hash[$offset+3]) & 0xff)
	    ) % pow(10, self::otpLength);
	}



}

Step 2 : Create another file where you want to implement it , and on that file at the top include this file Google2FAClass.php and Set The Initial Key for further use it should be unique for each project, It’s important key so make it private.

$InitalizationKey = "PEHMPSDNLXIOG65U";

Step 3: Get current time-stamp, it’s very useful to generate one time tokens according to the current time-stamp.

$TimeStamp	  = Google2FA::get_timestamp();

Step 4: Decode into binary

$secretkey 	  = Google2FA::base32_decode($InitalizationKey);

Step 5: Get OTP / Current Token

$otp = Google2FA::oath_hotp($secretkey, $TimeStamp);

Step 6: Verify Current Token , Use this code to verify a key as it allows for some time drift.

$result = Google2FA::verify_key($InitalizationKey, "123456");

Save OTP To Database as Temporary Value / Data

Now we have OTP Pin Code, It’s time to save this code over our database. If you have an wordpress site and you are using this api for any user authentication or user session / transaction management you can save it with :

update_user_meta($user_ID, 'otp_payment','$otp_code'); // For wordpress user's OTP management

$query = mysql_query("UPDATE otp_table SET otp_code='".$otp_code."' WHERE user_id= '$user_ID' ");// For PHP USER's OTP MANAGEMENT

Send OTP to Users Using Email

After creating otp pin code and saving it to database it’s time to notify your customer / website user. So send email to their email id by using below code:

$customer_email = "customer_name@example.com";

$emailSubject = "Hello, We received an Authentication Request."

$emailContent = "Thanks to request an OTP, Your OTP Code for this transaction is $otp_code";
mail($customer_email ,$emailSubject ,$emailContent); // Using mail() Function to send otp pin via email

SMS Api Integration to Send OTP to Users Mobile

Here we read how to create otp pin and then we saved that otp pin to database, now it’s time to send otp code via SMS to user’s mobile no. To send otp code via mobile we have to integrate sms api first, so below you can see “How to Integrate SMS Api Using PHP“:

function sendSMS($mobile=null, $subject=null)
{
$SMSapiKey = 'XYZ';
$url = 'http://example.com/api_2.0/SendSMS.php?APIKEY='.$SMSapiKey.'&MobileNo='.urlencode($mobile).'&SenderID=SAMPLE_MSG&Message='.urlencode($subject).'&ServiceName=TEMPLATE_BASED';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec($ch);
curl_close($ch);
return "A SMS SENT SUCCESSFULLY TO $mobile";
}

You have to call this function sendSMS(), to send SMS using php code. You can easily send an otp code to user/customers via this function, but you must have an working sms api with a bulk sms service. You can change $url variable with your sms provider’s api url.

Now here is an example how can you use this function :

sendSMS(123456789, "Hello, Your OTP (One Time Password) for this transaction is $otp_code");

So here you can use this whole code to create a best otp system in your website.

Conclusion and Final Code:

//OTP SYSTEM CODE

function sendSMS($mobile=null, $subject=null)
{
$SMSapiKey = 'XYZ';
$url = 'http://example.com/api_2.0/SendSMS.php?APIKEY='.$SMSapiKey.'&MobileNo='.urlencode($mobile).'&SenderID=SAMPLE_MSG&Message='.urlencode($subject).'&ServiceName=TEMPLATE_BASED';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec($ch);
curl_close($ch);
return "A SMS SENT SUCCESSFULLY TO $mobile";
}
$otp_code = strtoupper(bin2hex(openssl_random_pseudo_bytes(3)));  // A smart code to generate OTP PIN.

//update_user_meta($user_ID, 'otp_payment','$otp_code'); // For wordpress user's OTP management
$query = mysql_query("UPDATE otp_table SET otp_code='".$otp_code."' WHERE user_id= '$user_ID' ");// For PHP USER's OTP MANAGEMENT

$otp_query_fetch = mysql_query($query);

//Send OTP Via Email

$customer_email = "customer_name@example.com";

$emailSubject = "Hello, We received an Authentication Request."

$emailContent = "Thanks to request an OTP, Your OTP Code for this transaction is $otp_code";
mail($customer_email ,$emailSubject ,$emailContent); // Using mail() Function to send otp pin via email

// Send OTP Via SMS

sendSMS(123456789, "Hello, Your OTP (One Time Password) for this transaction is $otp_code");

echo "An OTP has been sent to your mobile and email.";

In this entire article we have learned about how to make otp in php since last 1 year lot’s of users tried my code to create their awesome and secured one time password system. But as i told you guys to very soon i will be back with plugins for otp code development so before working on production of this new product i want your suggestion. Please keep in mind your suggestion is too much important for me here. I love to support for further and want your awesome feedback on this entire content.

So as we studied here how we can create an OTP System using php by just few simple steps, generate otp pin, save otp as a temporary data in database and send it to user via sms or email. So here it was a simple way to make an otp system by php. Hope you liked this post and it was helpful for you, so if you really liked this post , so don’t forget to share it with your friends over facebook, google+ and your website. Here you can see demo of otp login system using php. As I shared a basic code apart from Google TOTP 2FA implementation, is a basic program, don’t use it for production, use it on your own risk, because it’s just a basic otp system, you can use it with Google 2FA implementation just replace $otp_code with Google TOTP 2FA’s token value.

69 Replies to “How to Make OTP (One Time Password) System Using Php

    1. Hello rob as per last discussion on fb, I already told you i am working on cryptographically secure code. Thanks to read this post

  1. I like this otp generation . I am novice learner I have to learn php like this type ,can I contact to you for any query in php development. and web development.
    Thank you very much.

  2. Should have been named how to generate random number rather.

    You are teaching about otp without recommending bulk sms services and their API.

    You better be descriptive and also explain to your readers about sendmail API. Not all webhost gives you that!

    Better edit this and also inform readers of your post about security because this thing can easily be hijacked and hacked and i didn’t read any line that adds disclaimer for unsecurity. One can easily hold you responsible for this so please be descriptive and add disclaimer next time!

    Hope am not misunderstood!

    1. Even SMS is insecure though. techcrunch.com/2016/07/25/nist-declares-the-age-of-sms-based-2-factor-authentication-over/

  3. The author of this article is not an expert in any sense of the word. If you are reading this post, forget everything he said.

    1. function sendSMS($mobile=null, $subject=null) { $SMSapiKey = 'XYZ'; $url = 'http://example.com/api_2.0/SendSMS.php?APIKEY='.$SMSapiKey.'&MobileNo='.urlencode($mobile).'&SenderID=SAMPLE_MSG&Message='.urlencode($subject).'&ServiceName=TEMPLATE_BASED'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $returndata = curl_exec($ch); curl_close($ch); return "A SMS SENT SUCCESSFULLY TO $mobile"; }

      call this function after generating otp code. and send sms to users mobile.

      But before doing this you must need an sms gateway, or sms api with working sms plan.

  4. Hello, Rahul!

    Thanks for sharing your code.

    But im litttle confused with how to use your example attached here ?

    What i need to change in code and how to create required tables (maybe, automaticaly?) to work it out on my own server ?

    Thanks in advance! =)
    Regars, BJ

    1. Yeah thanks BJ, to share your experience with me, Yes sure i will upload db structure with you here soon.

      Your Most Welcome

  5. Hello, Rahul!

    Thanks for sharing your great code!
    Can you explain me how the function oath_truncate() work, i mean what happens if i use the $hash as OTP code?

    Thank you!

  6. Hii bro
    Your code is ok working but when we enter the mailid and send the otp to reg mailid after its going to your website page and app.js file is not there when we downloaded the file..

    Pls say how to do this..

    1. Hii sorry now its working fine i have changed

      But i have an doubt otp is inserting in the DB but mail not receving pls help me

    1. Yes sure it’s possible as i always tell you about PHP Scripting and honestly if you want any modification “OTP system in PHP” you can ask me anything, Have a good day ahead.

      1. i just wanted to understand the process of otp verification for mobile number.
        is it chargable? i wanted to create a registration form in we will verify user mobile no using otp. can you please help how to move further.?
        Thanks

        1. you just need to get an sms api for mobile otp verification, code will be same before mail() function you need to add SendSmsFunction as it is mentioned in article above

  7. please help the script i download is not working the landing page is ok but once i entered the email and click on send otp the following message appears

    Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.
    Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.

  8. Hi , I have some problem implement the OTP Function inside my code, I have been searching everywhere but none of it seems working , here is my code:

    stackoverflow[dot]com/questions/52148802/otp-integration-at-registration-form/52148993#52148993

    “I am having trouble integrating the “send OTP” function in my registration form. I was given an API from an SMS provider, but I do not know how to integrate it into my form. I need the user data to be recorded in my database after the verify the OTP. But how the verify process work? and how does the system would generate 6 digits random code to the user? I have been trying a different method and search online but none of that is working. Can anyone help?

  9. you just need to get an sms api for mobile otp verification, code will be same before mail() function you need to add SendSmsFunction as it is mentioned in article above

        1. I did , but failed.
          What I am trying to achieve is :
          First: the user register at my form
          Second: at the same form beside the phone number box has a send otp button and when it clicked , an otp will sent to users phone
          Third :the user key in the otp and clicked submit and all the data will be recorded at my database

        2. Louis it’s so simple you need to understand the method / the way how it works “Actually otp works on a random string system where we generate a new string according to some parameters as if you are doing it for production mode you can use above given G2FAClass.php code” and generate a code.

          Okay such as i am inserting a user’s data for first time and providing them a code after inserting it to users Table in database where i will also generate a unique activation code user id and a otp code ” I will create a otp code / uac and user id which will be (AI Field) so i will make a another table with a foreign key uac and where will be column like UAC/ OTP and STATUS OF OTP”
          Such as for user A I will put there
          In User table I will put =>
          User ID 1
          Name: Xyz
          Mobile: 123456789
          Password : XYZ
          UAC : XYZ (A UNIQUE CODE MUST BE 16 Char)
          USER STATUS : 1(Active)/2 Inavtice

          Now the time for next table
          REG OTP TABLE

          COLUMN
          OTP_ID = 1
          OTP_CODE = 456783
          OTP_STATUS = 1 (1 for sent / 2 for validate)
          UAC = XYZ (A FOREIGN KEY)

          Now hope you got what you have to do

          When you will send api =>
          USING G2FA => Create OTP CODE of 6 Digit
          Before Sending SMS => Save User Data for future purpose (Insert to user table and also insert to otp table)
          Using SMS API => Create A Function As I have created before in article to send sms via api (PUT OTP CODE VARIABLE HERE )
          Create Verification Form with =>
          compare UAC with OTP Table and if it will return result with otp status 1 then verify provided code and Mobile Number Check with mobile number (123456789) and UAC
          Update Verified => update user table otp status 1 and user status 1 in user table
          That’s done

          Feel free to contact again hope it will make good sound

  10. Hi, please I really need help with a php codeigneter script on OTP integration.. this is my login script
    load->library(‘session’);
    $this->load->helper(‘url’);
    $this->load->model(‘LoginModel’);
    }

    public function index()
    {
    if(empty($this->session->userdata(‘user_id’)))
    {
    $data=array();
    $data[‘title’]=”Login”;
    $this->load->view(‘template/header’,$data);
    $this->load->view(‘login’,$data);
    $this->load->view(‘template/footer’,$data);
    }
    else {
    redirect(‘dashboard’);
    }
    }
    public function logout()
    {
    $UserID=$this->session->userdata(‘user_id’);
    $data=array(
    ‘login_status’=>’0’,
    ‘activity_time’=>date(‘Y-m-d H:i:s’)
    );
    //print_r($data);die;
    $this->db->where(‘user_id’,$UserID);
    $this->db->update(‘tbl_users’,$data);

    $this->session->sess_destroy();
    redirect(base_url().’login/index’);

    }

    public function login_data()
    {
    $username = $this->input->post(‘username’);
    $mypassword = sha1($this->input->post(‘password’));
    $userDetails=$this->LoginModel->getUserDetailByEmail($username);

    if($userDetails)
    {
    $EmailVerifyCode = $this->LoginModel->getLatestEmailVerifyCodeByUserId($userDetails[0]->user_id);
    $loginHistory=$this->LoginModel->checkLoginHistoryByUserId($userDetails[0]->user_id);

    if($loginHistory>0)
    {
    $UserLoginDetails=$this->LoginModel->getUserLoginDetl($username,$mypassword);
    if($UserLoginDetails)
    {
    /* START:: User Login Session Check */
    /* if($UserLoginDetails[0]->login_status==1)
    {
    $this->session->set_flashdata(‘LoginError’, ‘User already logged in on another device/browser’);
    redirect(base_url().’Login’);
    }
    else
    {
    $UserLoginStatusUpdate=$this->LoginModel->getUserLoginDetlloginstatusupdate($username,$mypassword);
    } */
    /* END:: User Login Session Check */

    $this->session->set_userdata(array(
    ‘user_id’ => $userDetails[0]->user_id,
    ’email’ => $username,
    ‘role_id’=> $UserLoginDetails[0]->role_id,
    ‘registrar_id’=> $UserLoginDetails[0]->registrar_id,
    ‘admin_first_name’=> $userDetails[0]->admin_first_name,
    ‘first_login’=> ‘1’
    ));
    if($UserLoginDetails[0]->role_id==’2′)
    {
    redirect(base_url().’Manager/schedule_sheeet’);
    }
    else if($UserLoginDetails[0]->role_id==’3′)
    {
    redirect(base_url().’Dividend/company_list_dividendwise’);
    }
    else
    {
    redirect(base_url().’dashboard’);
    }
    }
    else if($EmailVerifyCode[0]->email_code == $this->input->post(‘password’))
    {
    if($loginHistory>0)
    {
    $this->session->set_flashdata(‘LoginError’, ‘Please enter valid Email ID and password’);
    redirect(base_url().’Login’);
    }
    else {

    /* END:: User Login Session Check */
    /*if($userDetails[0]->login_status==1)
    {
    $this->session->set_flashdata(‘LoginError’, ‘User already logged in on another device/browser’);
    redirect(base_url().’Login’);
    }
    else
    {
    $UserLoginStatusUpdate=$this->LoginModel->getUserLoginDetlloginstatusupdateByUserName($username);
    }*/
    /* END:: User Login Session Check */

    $this->session->set_userdata(array(
    ‘user_id’ => $userDetails[0]->user_id,
    ’email’ => $username,
    ‘role_id’=> $userDetails[0]->role_id,
    ‘registrar_id’=> $userDetails[0]->registrar_id,
    ‘admin_first_name’=> $userDetails[0]->admin_first_name,
    ‘first_login’=> ‘0’
    ));
    //redirect(base_url().’changepassword’);
    redirect(base_url().’Changepwd/index’);
    }

    }
    else
    {
    $this->session->set_flashdata(‘LoginError’, ‘Please enter valid email ID and password’);
    redirect(base_url().’Login’);
    }
    }
    else
    {
    if($EmailVerifyCode[0]->email_code == $this->input->post(‘password’))
    {

    $loginHistory_again=$this->LoginModel->checkLoginHistoryByUserId($userDetails[0]->user_id);
    if($loginHistory_again>0)
    {
    $this->session->set_flashdata(‘LoginError’, ‘Please enter valid email ID and password’);
    redirect(base_url().’Login’);
    }
    else
    {
    $dbrdata=array(
    ‘password’ =>sha1($EmailVerifyCode[0]->email_code),
    ‘status’ => ‘1’
    );
    $this->LoginModel->approveUserUpdPassword($dbrdata,$userDetails[0]->user_id);
    $UserLoginDetl=$this->LoginModel->getUserLoginDetl($username,$EmailVerifyCode[0]->email_code);

    /* END:: User Login Session Check */
    /* if($UserLoginDetl[0]->login_status==1)
    {
    $this->session->set_flashdata(‘LoginError’, ‘User already logged in on another device/browser’);
    redirect(base_url().’Login’);
    }
    else
    {
    $UserLoginStatusUpdate=$this->LoginModel->getUserLoginDetlloginstatusupdate($username,$EmailVerifyCode[0]->email_code);
    } */
    /* END:: User Login Session Check */

    $this->session->set_userdata(array(
    ‘user_id’ => $userDetails[0]->user_id,
    ’email’ => $username,
    ‘role_id’=> $userDetails[0]->role_id,
    ‘registrar_id’=> $userDetails[0]->registrar_id,
    ‘admin_first_name’=> $userDetails[0]->admin_first_name,
    ‘first_login’=> ‘0’
    ));
    //redirect(base_url().’changepassword’);
    redirect(base_url().’Changepwd/index’);
    }
    }
    else
    {
    $this->session->set_flashdata(‘LoginError’, ‘Please enter valid email ID and password’);
    redirect(base_url().’Login’);
    }
    }

    }
    else
    {
    $this->session->set_flashdata(‘LoginError’, ‘Please enter valid email ID and password’);
    redirect(base_url().’Login’);
    }
    }
    public function forget_password(){
    // $res = $_POST[’email’];
    $data[‘title’]=”Forgot Password”;
    $res = $this->input->post(’email’);
    if($res)
    {
    $email_exit=$this->LoginModel->getEmailExist($res);
    if($email_exit>0)
    {
    $this->db->select(“email,password,user_id”);
    $this->db->from(‘tbl_users’);
    $this->db->where(’email’,$res);
    $query = $this->db->get();
    $email_id = $query->result();
    $alphabet = “abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$&”;
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) – 1; //put the length -1 in cache
    for ($i = 0; $i < 12; $i++)
    {
    $n = rand(0, $alphaLength);
    $pass[] = $alphabet[$n];
    }
    $rand_pass = implode($pass);
    //echo " qwe”; print_r($pass); print_r($link); die;
    $user_id = $email_id[0]->user_id;
    $link = base_url().”forgetpassword/$user_id”;
    $msg = “Dear User\nThis is to inform you that you have requested for new password on Firs.\nPlease click here to redirect to Tax Connect Portal or copy and paste below given URL in your web browser.\n $link \nThanks\nTax Connect Portal”;
    // use wordwrap() if lines are longer than 70 characters
    $msg = wordwrap($msg,700);
    // send email
    mail($res,”Recovery Mail”,$msg);

    $currentDate=strtotime(date(“Y-m-d H:i:s”));
    $code_expire_time = date(“Y-m-d H:i:s”,$currentDate+(60*60));

    $data=array(’email’=> $res,
    ‘status’=>’0’,
    ‘code’=> $rand_pass,
    ‘expiry_date’=> $code_expire_time
    );
    $this->db->insert(‘tbl_pass_recovery’,$data);
    echo 200;
    }
    else
    {
    echo 400;
    }
    }
    else
    {
    echo 400;
    }

    }

    public function forgot_pass($vr=”){
    $data=array();
    $data[‘title’]=”Forgot Password”;
    $data[‘specicode’]=$vr;
    $this->load->view(‘template/header’,$data);
    $this->load->view(‘forgetpassword’,$data);
    $this->load->view(‘template/footer’,$data);

    }

    public function change_pass(){

    $specicode=$this->input->post(‘specicode’);
    if($specicode){
    $this->db->select(“user_id,email”);
    $this->db->from(‘tbl_users’);
    $this->db->where(‘user_id’,$specicode);
    $query = $this->db->get();
    $user_id = $query->result();

    /*——-get data to check status ——— */
    $this->db->select(“email,status”);
    $this->db->from(‘tbl_pass_recovery’);
    $this->db->where(’email’,$user_id[0]->email);
    $query2 = $this->db->get();
    $status = $query2->result();
    if($status[0]->status==’0′){

    $mypassword = sha1($this->input->post(‘newpass’));
    $dataUpdt=array(‘password’=> $mypassword);
    $this->db->where(‘user_id’,$specicode);
    $this->db->update(‘tbl_users’,$dataUpdt);
    /*—————– Verified data status ————–*/
    $statusdata=array(‘status’=> ‘1’);
    $this->db->where(’email’,$user_id[0]->email);
    $this->db->update(‘tbl_pass_recovery’,$statusdata);

    }
    redirect(base_url());
    }else{
    $this->session->set_flashdata(‘Error’, ‘Please click on the link enclosed in the mail sent on your registered Email ID’);
    redirect(base_url().’forgetpassword’);
    }
    }
    }

  11. Hi Rahul, Can I use this code in Arduino programming.
    Actually, I am making Door unlocking system using OTP generation so can I use this with Arduino or any other processor

  12. Hi Rahul, please can you share me your whatsapp no, lets chat. I have some other few questions to ask. +2347062705765 msg on whatsapp

Leave a Reply to Louis Cancel reply

Your email address will not be published.