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.

php Courses
php Courses
php Courses
How to Generate and Decode QR Codes in PHP with Simple Code Examples

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 image

The 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 result

This 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Image ProcessingPHPQR codeZXingQRCode library
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.