Generating and Decoding QR Codes in PHP
This article explains how to use PHP functions and open‑source libraries to generate QR code images and decode them back into text, providing step‑by‑step code examples for both creation and decoding processes.
With the widespread use of smartphones, QR codes have become a practical way to transmit information, and PHP can be used to both generate and decode them. The following guide shows how to include the necessary libraries and call the appropriate functions.
1. Generate QR Code
In PHP, the QRCode class from the qrcode.php library is used. After requiring the library, you can call QRCode::png() with the desired text and output filename to create a QR code image.
require 'qrcode.php';
$text = 'https://example.com'; // QR code content
$filename = 'qrcode.png'; // output file name
QRCode::png($text, $filename); // generate QR code imageThe code first includes qrcode.php , defines the content ( $text ) and the filename ( $filename ), and then generates the PNG image by invoking QRCode::png() .
2. Decode QR Code
Decoding a QR code in PHP is straightforward using the imagecreatefrompng() function to load the image and the ZXing library’s decode() method to extract the embedded text.
require 'qrcode.php';
require 'zxing.php';
$filename = 'qrcode.png'; // QR code image path
$im = imagecreatefrompng($filename); // create image resource
$decoded_text = ZxingDecoder::decode($im); // decode QR code
imagedestroy($im); // free resource
echo $decoded_text; // output resultThe script includes both qrcode.php and zxing.php , loads the PNG file, decodes it with ZxingDecoder::decode() , releases the image resource, and finally prints the decoded text.
These examples demonstrate the basic steps for generating and decoding QR codes in PHP, and they can be extended or customized to fit more complex application requirements.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.