Current Location: Home> Latest Articles> How to Generate Expiring QR Codes with PHP

How to Generate Expiring QR Codes with PHP

M66 2025-07-27

How to Generate Expiring QR Codes with PHP

QR codes have become widely used in modern applications such as mobile payments and electronic tickets. In some cases, we may need to generate QR codes with an expiration time, so that the code will become invalid after a certain period. This article will guide you on how to implement this using PHP.

Install the PHP QR Code Library

To generate QR codes in PHP, you first need to install the PHP QR Code library. This open-source PHP class library makes it easy to generate QR codes. You can download the library from GitHub and extract it to your server directory.

Generate Expiring Text

Before generating a QR code, you need to create the text with the expiration information. This text often includes details such as the expiration time, encrypted data, etc.

// Generate text with expiration information
$expireTimestamp
$data

In this code, we use the time() function to get the current timestamp and add 3600 seconds (1 hour) to set the expiration time. We then concatenate the data to be encoded with the expiration time.

Generate the QR Code

Once the text with expiration information is generated, we can use the PHP QR Code library to generate the corresponding QR code. Here's a code example for generating the QR code:

// Include the QR Code library
require_once
// Generate the QR code
$qrCodePath
QRcode::png(

In this code, we first include the PHP QR Code library with require_once, and then call the QRcode::png() function to generate the QR code. The function parameters include the data to encode, the save path, the error correction level (QR_ECLEVEL_L represents the lowest level), and the size of the QR code.

Validate QR Code Expiration

After generating the QR code, we need to validate its expiration when the QR code is scanned. Here's an example code for checking whether the QR code has expired:

// Validate if the QR code has expired
$qrCodePath
$expireTimestamp
if
    
    
} 
    
    
}

This code checks if the QR code file exists using the file_exists() function, and retrieves the file's modification time using filemtime(). Then, it compares the current timestamp with the expiration time to determine whether the QR code has expired.

Conclusion

This article introduced how to generate QR codes with an expiration time using PHP. After installing the PHP QR Code library, we can easily generate QR codes and set expiration times. By verifying the file's timestamp, we can ensure that the QR code is invalid after the expiration time. We hope this guide helps you implement this feature in your projects.