Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active August 7, 2023 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/060bf3759c3bae061ebcd529b63d8dcf to your computer and use it in GitHub Desktop.
Save code-boxx/060bf3759c3bae061ebcd529b63d8dcf to your computer and use it in GitHub Desktop.
PHP MYSQL One Time Password (OTP)

PHP MYSQL ONE TIME PASSWORD (OTP)

NOTES

  1. Create a test database and import the 1-database.sql file.
  2. Change the database settings in 2-otp.php to your own.
  3. Launch 3a-request.php to generate an OTP request, 3b-challenge.php for the challenge.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `otp` (
`email` varchar(255) NOT NULL,
`pass` varchar(255) NOT NULL,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `otp`
ADD PRIMARY KEY (`email`);
<?php
class OTP {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = "";
function __construct() {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE CONNECTION
function __destruct() {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER - RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GENERATE OTP
function generate ($email) {
// (D1) CHECK EXISTING OTP REQUEST
$this->query("SELECT * FROM `otp` WHERE `email`=?", [$email]);
$otp = $this->stmt->fetch();
if (is_array($otp) && (strtotime("now") < strtotime($otp["timestamp"]) + (OTP_VALID * 60))) {
$this->error = "You already have a pending OTP.";
return false;
}
// (D2) CREATE RANDOM OTP
$alphabets = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$count = strlen($alphabets) - 1;
$pass = "";
for ($i=0; $i<OTP_LEN; $i++) { $pass .= $alphabets[rand(0, $count)]; }
$this->query(
"REPLACE INTO `otp` (`email`, `pass`) VALUES (?,?)",
[$email, password_hash($pass, PASSWORD_DEFAULT)]
);
// (D3) SEND VIA EMAIL
if (@mail($email, "Your OTP",
"Your OTP is $pass. Enter at <a href='http://localhost/3b-challenge.php'>SITE</a>.",
implode("\r\n", ["MIME-Version: 1.0", "Content-type: text/html; charset=utf-8"])
)) { return true; }
else {
$this->error = "Failed to send OTP email.";
return false;
}
}
// (E) CHALLENGE OTP
function challenge ($email, $pass) {
// (E1) GET THE OTP ENTRY
$this->query("SELECT * FROM `otp` WHERE `email`=?", [$email]);
$otp = $this->stmt->fetch();
// (E2) CHECK - NOT FOUND
if (!is_array($otp)) {
$this->error = "The specified OTP request is not found.";
return false;
}
// (E3) CHECK - EXPIRED
if (strtotime("now") > strtotime($otp["timestamp"]) + (OTP_VALID * 60)) {
$this->error = "OTP has expired.";
return false;
}
// (E4) CHECK - INCORRECT PASSWORD
if (!password_verify($pass, $otp["pass"])) {
$this->error = "Incorrect OTP.";
return false;
}
// (E5) OK - DELETE OTP REQUEST
$this->query("DELETE FROM `otp` WHERE `email`=?", [$email]);
return true;
}
}
// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (G) OTP SETTINGS
define("OTP_VALID", "15"); // otp valid for n minutes
define("OTP_LEN", "8"); // otp length
// (H) NEW OTP OBJECT
$_OTP = new OTP();
<!DOCTYPE html>
<html>
<head>
<title>OTP DEMO</title>
<meta charset="utf-8">
<link rel="stylesheet" href="x-dummy.css">
</head>
<body>
<!-- (A) OTP REQUEST FORM -->
<form method="post" target="_self">
<label>Email</label>
<input type="email" name="email" required value="jon@doe.com">
<input type="submit" value="Request OTP">
</form>
<?php
// (B) PROCESS OTP REQUEST
if (isset($_POST["email"])) {
require "2-otp.php";
$pass = $_OTP->generate($_POST["email"]);
echo $pass ? "<div class='note'>OTP SENT.</div>" : "<div class='note'>".$_OTP->error."</div>" ;
}
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>OTP DEMO</title>
<meta charset="utf-8">
<link rel="stylesheet" href="x-dummy.css">
</head>
<body>
<!-- (A) OTP CHALLENGE FORM -->
<form method="post" target="_self">
<label>Email</label>
<input type="email" name="email" required value="jon@doe.com">
<label>OTP</label>
<input type="password" name="otp" required>
<input type="submit" value="Go">
</form>
<?php
// (B) PROCESS OTP CHALLENGE
if (isset($_POST["email"])) {
require "2-otp.php";
$pass = $_OTP->challenge($_POST["email"], $_POST["otp"]);
// @TODO - DO SOMETHING ON VERIFIED
echo $pass ? "<div class='note'>OTP VERIFIED.</div>" : "<div class='note'>".$_OTP->error."</div>" ;
}
?>
</body>
</html>
/* (X) NOT IMPORTANT - COSMETICS */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
max-width: 400px;
padding: 10px;
}
form {
padding: 20px;
border: 1px solid #eee;
background: #f7f7f7;
}
label, input {
display: block;
width: 100%;
}
label { margin: 10px 0; }
label:first-child { margin-top: 0; }
input[type=email], input[type=password] {
padding: 10px;
border: 1px solid #cbcbcb;
font-size: 1em;
}
input[type=submit] {
padding: 10px;
margin-top: 20px;
border: 0;
color: #fff;
background: #566cdb;
cursor: pointer;
}
div.note {
margin-top: 20px;
padding: 10px;
color: #333;
border: 1px solid #ffbcbc;
background: #ffe0e0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment