Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thilinathushan's avatar

Generate QR codes dynamically

I want to generate QR codes dynamically, that must be changed every 30seconds. In a QR code, there will be a random OTP PIN.

0 likes
4 replies
Tharshini_95's avatar

Here is an example in Python using the qrcode and pyotp libraries:

import qrcode
import pyotp
import time

# generate a random base32 secret key for the OTP
secret = pyotp.random_base32()

while True:
    # generate a new OTP every 30 seconds
    totp = pyotp.TOTP(secret)
    otp = totp.now()

    # create a QR code with the OTP as its data
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(otp)
    qr.make(fit=True)

    # print the QR code as ASCII art
    print(qr.get_ascii())

    # wait for 30 seconds before generating a new OTP and QR code
    time.sleep(30)
1 like
Tharshini_95's avatar

@thilinathushan yes, you can generate QR codes dynamically in Laravel using the SimpleSoftwareIO\QrCode package. Here's how you can do it:

First, install the SimpleSoftwareIO\QrCode package using Composer:

composer require simplesoftwareio/simple-qrcode

Second, create a route in your Laravel application to generate the QR code with a random OTP PIN:

use SimpleSoftwareIO\QrCode\Facades\QrCode;

Route::get(''/qr-code',  function () {
   $otp = mt_rand(100000, 99999); // generate a random OTP PIN
   return response(QrCode::size(250)->generate('otp:' . $otp))->header('Content-Type', 'image/png');
});

--> This code will generate a random OTP PIN and return a QR code image with the text otp: followed by the OTP PIN.

Third, in your view, add an image tag with the src attribute set to the URL of the route that generates the QR code:

<img src="/qr-code" alth="QR code">

Fourth, to refresh the QR code every 30 seconds, you can use JavaScript to replace the src attribute of the img tag with the URL of the route that generates the QR code:

setInerval(function (){
   document.querySelector('img').src = '/qr-code?' + new Date().getTime();
}, 30000);

-->This code will replace the src attribute of the img tag with the URL of the route that generates the QR code every 30 seconds. The new Date().getTime() part is added to the URL as a query parameter to prevent caching of the image.

--> That's it! Now you have a QR code that changes every 30 seconds with a random OTP PIN.

I hope this helps you.

1 like
martinbean's avatar

@thilinathushan Just use a Laravel authentication package that already does this for you. Because OTP codes are not random; they’re based on a cryptographic algorithm that’s partially based on the current time for synchronisation.

So please don’t try and roll your own OTP solution, because it won’t be as secure and as tested as a pre-made one, and you could end up weakening the security of your application and users if implemented incorrectly.

1 like

Please or to participate in this conversation.