How to Generate and Decode QR Codes in PHP with Simple Code Examples
This guide explains how to use the open‑source QRCode library in PHP to create QR code images with QRCode::png() and how to decode them using imagecreatefrompng() together with the ZXing library, providing complete code snippets and step‑by‑step instructions.
With the widespread use of smartphones, QR codes have become a practical way to transmit information, and PHP can both generate and decode them using simple functions.
1. Generate QR Code
First, include the open‑source qrcode.php library (available on GitHub). Then call QRCode::png() with the desired text and an 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 loads the library, defines the content and filename, and generates the PNG file containing the QR code.
2. Decode QR Code
Decoding is straightforward: use PHP's imagecreatefrompng() to load the QR image, then employ the ZXing library’s decode() method to extract the embedded text.
require 'qrcode.php';
require 'zxing.php';
$filename = 'qrcode.png'; // path to QR code image
$im = imagecreatefrompng($filename); // create image resource
$decoded_text = ZxingDecoder::decode($im); // decode QR code
imagedestroy($im); // free image resource
echo $decoded_text; // output decoded resultThis snippet loads both the QR code generation and ZXing decoding libraries, creates an image resource from the PNG file, decodes the QR code, releases the resource, and prints the original text. In real applications you can further customize the QR code generation parameters or handle decoding errors as needed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
