With the widespread adoption of mobile and scan payments, QR codes have become an essential part of daily life. Integrating QR code generation into websites and applications is increasingly necessary. PHP offers multiple open-source libraries that make generating QR codes straightforward. This article explains how to quickly generate QR codes using the PHP QR Code library.
Before implementing QR code functionality, you need to install the PHP QR Code library. It can be freely downloaded from GitHub or installed via Composer. If you have Composer installed, run the following command:
<span class="fun">composer require t0k4rt/phpqrcode</span>
If not using Composer, you can download the library directly from GitHub, extract it, and include the phpqrcode.php file in your project to use.
Once installed, you can start generating QR codes. The main steps are:
Make sure to include the phpqrcode.php file in your PHP code, usually with require_once:
<span class="fun">require_once 'phpqrcode.php';</span>
The QRcode::png() function accepts the following parameters:
Example generating QR code to a file:
$text = 'https://www.baidu.com/';
$file = 'qrcode.png'; // Filename and path
$level = 'L'; // Error correction level: L, M, Q, H
$size = 10; // QR code size: 1-10
$margin = 1; // Margin: 1-10
<p>QRcode::png($text, $file, $level, $size, $margin);<br>
Example outputting QR code directly to browser:
$text = 'https://www.baidu.com/';
$level = 'L';
$size = 4;
$margin = 2;
<p>QRcode::png($text, false, $level, $size, $margin);<br>
Complete PHP example to generate a QR code:
require_once 'phpqrcode.php';
$text = 'https://www.baidu.com/';
$file = 'qrcode.png'; // Filename and path
$level = 'L'; // Error correction level: L, M, Q, H
$size = 10; // QR code size: 1-10
$margin = 1; // Margin: 1-10
<p>QRcode::png($text, $file, $level, $size, $margin);<br>
This article has shown how to use the PHP QR Code library to generate QR codes. The library is powerful and easy to use, supporting multiple styles such as QR codes with logos, background images, and Chinese characters. We hope this tutorial helps you successfully integrate QR code generation into your PHP projects.