chillerlan/php-qrcode
Generate and read QR codes in PHP. Supports Model 2 QR codes (versions 1–40), ECC levels L/M/Q/H, mixed encoding modes, and multiple output formats. Includes a QR code reader based on a PHP port of ZXing.
Installation:
composer require chillerlan/php-qrcode
Ensure PHP 8.4+ with ext-mbstring (required) and optionally ext-gd/ext-imagick for image output.
First Use Case: Generate a QR code for a URL in a Laravel Blade view:
use Chillerlan\QRCode\QRCode;
// In your controller
$qrCodeUrl = (new QRCode)->render('https://example.com', 'svg');
// In Blade
<img src="{{ $qrCodeUrl }}" alt="QR Code">
Key Files:
vendor/chillerlan/php-qrcode/src/ (Core classes)examples/ (GitHub repo) for advanced use casesQR Generation:
// Basic usage
$qr = new QRCode;
$qr->render('data', 'png'); // Returns data URI
// With options (via QROptions)
$options = new QROptions(['outputType' => 'png', 'size' => 300]);
$qr->render('data', $options);
Laravel Integration:
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(QRCode::class, function () {
return new QRCode(new QROptions(['outputType' => 'svg']));
});
}
// app/Helpers/qrcode.php
if (!function_exists('generate_qr')) {
function generate_qr(string $data, string $format = 'svg'): string
{
return app(QRCode::class)->render($data, $format);
}
}
Dynamic QR Codes:
qr_data column) and generate on-the-fly:
$qrData = $model->qr_data;
$qrUrl = generate_qr($qrData);
Reading QR Codes:
use Chillerlan\QRCode\QRReader;
$reader = new QRReader;
$result = $reader->readImage('path/to/qr.png'); // Returns decoded data
Custom Output Modules:
Extend QROutputModule for new formats (e.g., PDF via DomPDF):
class QRDompdf extends QROutputModule
{
public function render($data, $options): string
{
// Custom logic
}
}
Error Correction: Adjust ECC levels for robustness:
$options = new QROptions(['eccLevel' => 'H']); // High error correction
Multi-Format Support:
$formats = ['svg', 'png', 'jpg'];
$qrUrls = collect($formats)->map(fn($f) => generate_qr($data, $f));
Caching: Cache generated QR codes (e.g., Redis) to avoid reprocessing:
$cacheKey = 'qr_'.md5($data);
$qrUrl = cache()->remember($cacheKey, now()->addHours(1), function() use ($data) {
return generate_qr($data);
});
Output Format Mismatch:
ext-gd/ext-imagick is installed for image formats.svg (no extensions required) for compatibility.Data Encoding:
mailto:user@example.com?subject=Hello%20World).kanji), use 8-bit binary mode:
$options = new QROptions(['encodingMode' => 'binary']);
Reader Limitations:
svg for readability.QRReader::readImage() in a controlled environment.Version/Size Conflicts:
$qr->render($data, $options);
if ($qr->getError()) {
// Handle "version too low" errors
}
Validate Data:
Use QRCode::validateData() to check if data fits the QR capacity:
if (!QRCode::validateData('long_data_here', $options)) {
throw new \Exception('Data too long for selected options.');
}
Inspect Options:
Dump QROptions to verify settings:
dd($options->toArray());
Fallback Formats: Dynamically switch formats if primary fails:
try {
return generate_qr($data, 'png');
} catch (\Exception $e) {
return generate_qr($data, 'svg');
}
Custom Error Handling:
Override QRCode::render() to log errors:
$qr = new QRCode;
$qr->setErrorHandler(function($error) {
Log::error("QR Generation Error: {$error}");
});
Hooks for Post-Processing:
Use QROutputModule::postRender() to modify output (e.g., add watermarks):
class QRCustomOutput extends QROutputModule
{
public function postRender($output, $options)
{
return $this->addWatermark($output);
}
}
Performance:
svg for static QR codes (no image processing overhead).QRCode::renderMultiple():
$qr->renderMultiple(['data1', 'data2'], 'png');
Security:
QROptions::setStrictMode(true) to enforce validation.Storage Paths:
Save QR codes to storage/app/qr/:
$path = storage_path('app/qr/code_'.Str::uuid().'.png');
file_put_contents($path, $qr->render($data, 'png'));
Queue Jobs: Offload QR generation to queues for long-running tasks:
GenerateQRJob::dispatch($data, $userId)->onQueue('qr');
View Composers: Inject QR codes globally:
// app/ViewComposers/QRComposer.php
public function compose(View $view)
{
$view->with('qrUrl', generate_qr('default_data'));
}
API Responses: Return QR codes as attachments:
return response()->streamDownload(
fn() => echo $qr->render($data, 'png'),
'qr_code.png'
);
How can I help you explore Laravel packages today?