phpqrcode is a commonly used PHP library that allows for quick and easy QR code generation. It can be installed via Composer.
Install the library using Composer:
composer require bacon/qrcode
Once installed, you can use it in your project to generate QR codes.
Include the autoload file and use the necessary classes to generate a QR code:
require_once 'vendor/autoload.php';
use BaconQrCode\Renderer\Image\Png;
use BaconQrCode\Writer;
$renderer = new Png();
$renderer->setHeight(200);
$renderer->setWidth(200);
$writer = new Writer($renderer);
$writer->writeFile('QR code content', 'Path to save QR code');
This code creates a 200x200 QR code image and saves it to the specified path.
endroid/qrcode is another widely used PHP QR code library, offering more customization options.
Install the library using Composer:
composer require endroid/qrcode
After installation, you can start using it right away.
Create a QR code image with the following code:
use Endroid\QrCode\QrCode;
$qrCode = new QrCode('QR code content');
$qrCode
->setSize(200)
->setMargin(10)
->writeFile('Path to save QR code');
This code generates a 200-pixel QR code with a 10-pixel margin and saves it locally.
Google's Chart API also supports QR code generation and is a fast solution without external libraries.
Create a QR code using a simple URL and save the image content:
$qrCodeUrl = 'https://chart.googleapis.com/chart?cht=qr&chs=200x200&chl=QR code content';
file_put_contents('Path to save QR code', file_get_contents($qrCodeUrl));
This method is ideal for quick implementation without additional dependencies.
This article introduced three popular methods for generating QR codes in PHP: using the phpqrcode library, the endroid/qrcode library, and the Google Chart API. Each method has its own strengths, so developers can choose the one that best suits their project requirements.