Current Location: Home> Latest Articles> How to Generate and Decode QR Codes Using PHP Functions?

How to Generate and Decode QR Codes Using PHP Functions?

M66 2025-06-29

How to Generate and Decode QR Codes Using PHP Functions?

With the popularity of smartphones, QR codes have become a convenient tool for information transfer, widely used in payments, social interactions, advertisements, and more. So, how can we generate and decode QR codes in PHP? This article will show you how to use PHP functions to generate and decode QR codes, along with the relevant code examples.

Generating a QR Code

In PHP, QR codes can be generated using the QRCode class. First, you need to download and include an open-source QR code generation library (such as qrcode.php). After including the library, you can use the QRCode::png() function to generate a QR code.

Here is an example of code to generate a QR code:

require 'qrcode.php';

$text = 'https://example.com'; // QR code content

$filename = 'qrcode.png'; // Generated QR code image filename

QRCode::png($text, $filename); // Generate QR code image

In this code, we first include the qrcode.php file. Then we define the content of the QR code ($text) and the filename for the generated image ($filename). Finally, the QRCode::png() function is called to generate the QR code and save it as the specified file.

Decoding a QR Code

Decoding a QR code in PHP is relatively straightforward. First, use PHP's imagecreatefrompng() function to load the QR code image, and then use the ZXing library's decode() method to decode the QR code.

Here is an example of code to decode a QR code:

require 'qrcode.php';

require 'zxing.php';

$filename = 'qrcode.png'; // Path to the QR code image

$im = imagecreatefrompng($filename); // Create image resource

$decoded_text = ZxingDecoder::decode($im); // Decode the QR code

imagedestroy($im); // Release image resource

echo $decoded_text; // Output the decoded result

This code starts by including the qrcode.php and zxing.php files, loads the QR code image using imagecreatefrompng(), then decodes it using the ZxingDecoder::decode() function. Finally, it releases the image resource and outputs the decoded result.

Conclusion

With the above examples, you can easily implement QR code generation and decoding in PHP. Whether you want to generate QR codes for information transfer or decode QR codes to extract their content, PHP provides powerful support for these operations. We hope this article helps you better understand how to work with QR codes in PHP.