The release process is described here.
Please note that only versions listed in are maintained.
Older versions are not maintained anymore. You can create a Pull Request that may be considered, but without any guarantee.
This library needs at least PHP 8.1
.
The preferred way to install this library is to rely on Composer:
composer require spomky-labs/otphp
This library supports both TOTP
and HOTP
.
TOTP
is a time based one-time password. It lives only for a few seconds (the period
).
You just have to be sure that the clock of your server and your device are synchronized.
This is the most common OTP.
HOTP
is a counter based one-time password. Every time a password is used, the counter is updated.
You have to verify that the server and the device are synchronized.
To create an OTP object, just use the static generate
method. Your object will be able to generate passwords.
Note that the method will require a PSR-20 Clock in the next major release.
It is higly recommended to pass it as first argument to the generate
method in version 11.4+ to avoid any issue in the future.
<?php
use OTPHP\TOTP;
$clock = new MyClock(); // Your own implementation of a PSR-20 Clock
// A random secret will be generated from this.
// You should store the secret with the user for verification.
$otp = TOTP::generate($clock);
echo "The OTP secret is: {$otp->getSecret()}\n";
// Note: use your own way to load the user secret.
// The function "load_user_secret" is simply a placeholder.
$secret = load_user_secret();
$otp = TOTP::createFromSecret($secret, $clock);
echo "The current OTP is: {$otp->now()}\n";
In the example above, we use the TOTP
class, but you can use the HOTP
one the same way.
Then, you have to configure your applications.
You can use the provisioning Uri ($otp->getProvisioningUri();
) as QR Code input to easily configure all of them.
The provision URI can be stored in your database (or any other storage) and used to generate back the OTP object (see Factory).
We recommend you to use your own QR Code generator (e.g. [BaconQrCode](https://packagist.org/packages/bacon/bacon-qr-code) or [endroid/qr-code](https://github.com/endroid/qr-code)).
```php
<?php
// Note: You must set label before generating the QR code
$otp->setLabel('Label of your web');
$grCodeUri = $otp->getQrCodeUri(
'https://api.qrserver.com/v1/create-qr-code/?data=[DATA]&size=300x300&ecc=M',
'[DATA]'
);
echo "<img src='{$grCodeUri}'>";
Now that your applications are configured, you can verify the generated OTPs:
$otp = TOTP::createFromSecret($secret); // create TOTP object from the secret.
$otp->verify($input); // Returns true if the input is verified, otherwise false.
- Customization
- Application Configuration: get the provisioning Uri
- Factory: from a provisioning Uri to an OTP object
- Window: the window parameter
- Q&A: Questions and Answers