Current Location: Home> Latest Articles> Three Practical Ways to Generate QR Codes with PHP

Three Practical Ways to Generate QR Codes with PHP

gitbox 2025-08-04

Generating QR Codes Using the phpqrcode Library

phpqrcode is a commonly used PHP library that allows for quick and easy QR code generation. It can be installed via Composer.

Installing phpqrcode

Install the library using Composer:


composer require bacon/qrcode

Once installed, you can use it in your project to generate QR codes.

Generating a QR Code

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.

Generating QR Codes with endroid/QRcode

endroid/qrcode is another widely used PHP QR code library, offering more customization options.

Installing QRcode

Install the library using Composer:


composer require endroid/qrcode

After installation, you can start using it right away.

Generating a QR Code

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.

Using Google Chart API to Generate QR Codes

Google's Chart API also supports QR code generation and is a fast solution without external libraries.

Generating a QR Code

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.

Conclusion

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.