1. Go to this page and download the library: Download marektichy/totp-php library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
marektichy / totp-php example snippets
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Generate a new secret key for the user
$secret = $totp->generateSecret();
// Output the secret key
echo "Generated Secret Key: $secret\n";
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Example secret key
$secret = 'JBSWY3DPEHPK3PXP';
// Generate a TOTP code
$code = $totp->getCode($secret);
echo "Generated TOTP Code: $code\n";
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Example secret key and code
$secret = 'JBSWY3DPEHPK3PXP';
$code = '123456';
// Verify the code
$isValid = $totp->verifyCode($secret, $code);
echo $isValid ? "✅ Code is valid!\n" : "❌ Code is invalid!\n";
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Example secret key and user information
$secret = 'JBSWY3DPEHPK3PXP';
$uri = $totp->generateUri($secret, '[email protected]', 'YourApp');
echo "QR Code URI: $uri\n";
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
// Configure the time slice duration
$totp->configure(['period' => 60]);
$secret = $totp->generateSecret();
$code = $totp->getCode($secret);
echo "Generated TOTP Code (60-second period): $code\n";
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
$secret = 'JBSWY3DPEHPK3PXP';
$code = '123456';
// Allow discrepancy of 1 time slice
$isValid = $totp->verifyCode($secret, $code, 1);
echo $isValid ? "✅ Code is valid!\n" : "❌ Code is invalid!\n";
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
$secret = 'JBSWY3DPEHPK3PXP';
$code = '123456';
// Load the last accepted time slice from persistent storage (e.g. database).
// Use 0 on first login.
$lastAcceptedSlice = (int) $user->getLastTotpSlice();
$newSlice = $totp->verifyCodeOnce($secret, $code, $lastAcceptedSlice);
if ($newSlice === null) {
echo "❌ Code is invalid or has already been used!\n";
} else {
// Persist the new slice to block future reuse of this code.
$user->setLastTotpSlice($newSlice);
echo "✅ Code accepted!\n";
}
use RemoteMerge\Totp\Totp;
// Restrict the maximum allowed discrepancy to 2 time slices
$totp = new Totp(['max_discrepancy' => 2]);
$secret = $totp->generateSecret();
$code = $totp->getCode($secret);
// discrepancy of 1 is within the limit — works normally
$isValid = $totp->verifyCode($secret, $code, 1);
// discrepancy of 3 exceeds the limit — throws TotpException
$totp->verifyCode($secret, $code, 3);