PHP code example of esoftdream / otp

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

    

esoftdream / otp example snippets


use Esoftdream\OTP\OTP;

// Parameter: userType, userId
$otp = new OTP('member', 123);
$otp->type = 'forgot_password'; // Wajib set tipe kegunaan OTP

use Esoftdream\OTP\OTP;

// Parameter: userType, userId (null), db connection (null), identifier
$otp = new OTP('member', null, null, '[email protected]');
$otp->type = 'registration';

$otp->setLength(6)->setExpiry(5);

$result = $otp->generate();

/**
 * $result berisi:
 * [
 *    'otp' => '102678',
 *    'expired' => '2026-04-14 14:30:00'
 * ]
 */

try {
    // Input bisa berupa ' 10-26 78 ', akan tetap diproses sebagai '102678'
    if ($otp->verify($userInput)) {
        echo "OTP Berhasil divalidasi!";
    }
} catch (\Exception $e) {
    // Menangani error: 'Kode OTP tidak ditemukan', 'Kode OTP tidak valid', atau 'Kode OTP sudah kedaluwarsa'
    echo "Gagal: " . $e->getMessage();
}
bash
php spark migrate:latest -n Esoftdream\OTP
bash
./vendor/bin/phpunit tests/OTPTest.php