Skip to content

Instantly share code, notes, and snippets.

@dovidezra
Last active December 24, 2017 18:41
Show Gist options
  • Save dovidezra/130fa81ca15925b8553bec8700e5813d to your computer and use it in GitHub Desktop.
Save dovidezra/130fa81ca15925b8553bec8700e5813d to your computer and use it in GitHub Desktop.
(OTP-Auth) Easily Create One-Time Password System in PHP App
<?php
/**
* Name: (OTP-Auth) One-Time Password Authentication
* Auth: Jason Jersey
* Date: 12-24-2017
* Link: https://gist.github.com/icryptix/130fa81ca15925b8553bec8700e5813d
*/
/* Verifying whether OTP 1 hour cookie is set */
if(isset($_COOKIE["sitename_otp_cookie"])){
/* OTP Passthrough */
/* Display content to users who enter correct OTP code */
echo "HTML GOES HERE";
} else {
/* No Cookie Set */
/* Get Current Page URL */
$REQT_URI = $_SERVER['REQUEST_URI'];
/* Open Previously Started Session */
session_start();
/* Session Is Set */
if(isset($_SESSION['sitename_otp_user'])) {
if(isset($_POST['submitOTPcode']) && !empty($_POST['submitOTPcode'])){
if($_SESSION['sitename_otp_user'] == $_POST['submitOTPcode']) {
$cookie_value = $_POST['submitOTPcode'];
setcookie('sitename_otp_cookie',$cookie_value, time() + 3600, '/');
/* Refresh page */
header("Location: $REQT_URI");
} else {
echo "<div class='otp-error'>Incorrect OTP code entered. Try again!</div>";
}
}
echo "<div class='otp-code'>We've just emailed you a code to login. Please check your email now and enter the code below to safely access this site. This is an additional security messaure we take to protect your account.</div>";
echo "<form method='post'>";
echo "<input type='text' name='submitOTPcode' id='submitOTPcode' value='' placeholder='00000' size='5' maxlength='5'>";
echo "<input type='submit' value='Verify OTP'>";
echo "</form>";
} else {
/* Session Not Set */
$otpstr = '';
for($i=5;$i>0;$i--){
$otpstr = mt_rand(0,99999);
}
/* Prepare Email */
$from = 'support@example.com'; // Sent from the site
$to = 'example@gmail.com'; // Sent to the user
$subject = 'One-time Password for Login';
$body = 'Your one-time password is: '.$otpstr;
$headers .= 'From: '.$from. "\r\n" .
'Reply-To: '.$from. "\r\n";
/* Send Email */
mail($to, $subject, $body, $headers);
/* Start New Session */
session_start();
$_SESSION['sitename_otp_user'] = $otpstr;
/* Refresh page */
header("Location: $REQT_URI");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment