Generate QR code using PHP
Today, we’ll explain to you how to generate QR code using PHP.
A QR code (Quick Response code) is a type of matrix barcode used mostly for online shopping and digital payment. It is an optical label which contains some amount of information about the product or item.
In this article, we’ll show you simple ways to generate QR code in PHP. Here we will use the QR code generator PHP library.
Table of contents
1. Syntax
1 | QRcode::png($text, $filename, $err_correction, $pixel_size, $frame_size); |
2. Parameters
- $text: This is the input parameter for which the QR code needs to generate. It is a mandatory parameter.
- $filename: It specifies the path or location to save the generated QR code.
- $err_correction: It specifies the error correction capability of the QR code. There are 4 different levels of error correction.
- L[ow] – up to 7% damage
- M[edium] – up to 15% damage
- Q[uality] – up to 25% damage
- H[igh] – up to 30% damage
- $pixel_size: It specifies the pixel size of the QR code.
- $frame_size: It specifies the complete size of the QR code.
3. Example 1: Generate QR code
Let’s create a QR code with minimum code. Refer to the following file structure for example.
File Structure
- generate-qr-code-php
- library
- phpqrcode
- images
- index.php
- library
Click here to download QR code generator PHP library and add it under library
folder.
1 2 3 4 5 6 7 8 9 10 | <?php //include the qrlib file include './library/phpqrcode/qrlib.php'; // Set the data for QR $text = "CLUE MEDIATOR"; // Generate QR code QRcode::png($text); ?> |
The following output will appear when you run scripts that have default frame and pixel size.
4. Example 2: Store generated QR code in directory
In this example, we will create a QR code and store it in a given directory. Using the uniqid()
function, we will generate a unique name for the image based on microtime.
Let’s use the above file structure and update the following code in the index.php
file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php //include the qrlib file include './library/phpqrcode/qrlib.php'; // Set the data for QR $text = "CLUE MEDIATOR"; //path or location to save the generated QR code image. $path = 'images/'; // Create unique id using uniqid() function $filename = $path.uniqid().".png"; // set error correction level L $err_correction = 'L'; $pixel_size = 8; $frame_size = 8; // Generates QR Code and stores in given directory QRcode::png($text, $filename, $err_correction, $pixel_size, $frame_size); // Display QR code from directory echo "<center><img src='".$filename."'></center>"; ?> |
Run the above code and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂