QR codes are widely used in modern applications, from mobile payments and website logins to product tracking. This guide shows you how to generate and scan QR codes in PHP with simple, practical examples.
To handle QR codes in PHP, you’ll need two main libraries:
First, download the PHP QR Code library from GitHub and include it in your project. Then, make sure the PHP GD extension is enabled in your environment, as it’s required for image processing.
The following example demonstrates how to create a QR code image using the PHP QR Code library:
// Include the QR Code library
require_once('qrlib.php');
// Configuration
$text = 'https://example.com'; // Text content inside the QR code
$size = 10; // Size of the QR code in pixels
// Generate QR code image
$filename = 'qrcode.png';
QRcode::png($text, $filename, QR_ECLEVEL_L, $size);
echo 'QR code generated: ' . $filename;
This code generates a QR code image containing your specified text and saves it as a PNG file. You can output it directly to the browser or save it on the server for later use.
Once you’ve generated a QR code, you may want to decode it. ZBar is an open-source library that can read and recognize QR codes efficiently. It supports multiple programming languages and provides powerful decoding capabilities.
On Linux, you can install ZBar using your package manager. On Windows, download the precompiled binaries from the ZBar website and configure them for PHP.
The following example shows how to use the ZBar extension in PHP to scan a QR code image and extract its content:
// Create image resource
$image = imagecreatefrompng('qrcode.png');
// Initialize ZBar extension
$scanner = zbar_scanner_create();
zbar_scanner_set_config($scanner, 0, ZBAR_CFG_ENABLE, 1);
// Scan the image for QR codes
zbar_scan_image($scanner, $image); // Returns an array of results
// Retrieve recognition results
$results = zbar_get_results($scanner);
foreach ($results as $result) {
echo 'Detected: ' . $result->data . ' (Type: ' . $result->type . ')' . PHP_EOL;
}
// Release resources
zbar_image_destroy($image);
zbar_scanner_destroy($scanner);
When executed, this script loads the QR code image, scans it, and outputs the recognized data. If your QR code contains a URL or text, it will be displayed in the output.
With the methods described above, you can easily implement QR code generation and scanning in PHP. By combining the PHP QR Code library with ZBar, you can build efficient and flexible QR code features into your web projects or backend systems. Hopefully, this guide helps you get started with QR code development in PHP.