PHP code example of covaleski / otp

1. Go to this page and download the library: Download covaleski/otp 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/ */

    

covaleski / otp example snippets


use Covaleski\Otp\Totp;

// Define some settings.
$digits = 6;
$issuer = 'Foobar Inc.';
$label = 'Foobar: [email protected]';

// Create a secret.
$secret = '1234';

// Instantiate the TOTP class and get the URI.
$totp = new Totp($digits, $issuer, $label, $secret);
$uri = $totp->getUri();

use Covaleski\Otp\Totp;

// Instantiate the TOPT class.
$digits = 6;
$totp = new Totp(6, 'Cool LLC', 'Cool: [email protected]', $secret);

// Get the current password.
$input = (string) $_POST['code'];
$is_valid = $totp->getPassword() === $input;
echo 'Your code is ' . ($is_valid ? 'correct!' : 'incorrect!');

use Covaleski\Otp\Totp;

// Instantiate and configure.
$totp = new Totp(8, $issuer, $label, $secret);
$totp
    ->setStep(15)
    ->setOffset(3600);

class Totp extends Hotp
{
    // ...Other class members...

    /**
     * Get the current time counter.
     *
     * Returns the counter as a 8-byte binary string.
     */
    protected function getCounter(): string
    {
        // Get and offset the current UNIX timestamp.
        $time = time() + $this->offset;

        // Calculate the number of steps.
        $counter = floor($time / $this->step);

        // Format the number as an 8-byte binary string.
        $counter = dechex($counter);
        $counter = str_pad($counter, 16, '0', STR_PAD_LEFT);
        $counter = hex2bin($counter);

        return $counter;
    }

    /**
     * Get the URI for authentication apps.
     */
    public function getUri(): string
    {
        // Encode the secret as base32.
        $secret = Base32::encode($this->secret);
        $secret = str_replace('=', '', $secret);

        // Build URI.
        return $this->createUri('totp', [
            'secret' => $secret,
            'issuer' => $this->issuer,
            'algorithm' => 'SHA1',
            'digits' => $this->digits,
            'period' => $this->step,
        ]);
    }

    // ...Other class members...
}