For any developer knowing how to generate dynamic QR codes and allow users to download them as image files is an important task. QR codes are playing an important role in many industries like online payments, eCommerce, or ticket booking. Nowadays sharing QR codes on visiting cards is also very common.
The QR code stores some information in it and whenever someone scans it then they can use those data. Those data can be the serial no or addresses of the website. QR codes are two-dimensional barcodes that can be scanned by mobile phones or scanning machines.
In this article, we will see how to create or generate a QR code using PHP. There are many ready-to-use libraries available to create QR codes easily. In a further example, we will use the PHP QR Code library to create QR codes.
Before starting, you need to download and extract library files. Later on, we will use those files. You can use This link to download the library.
Generate QR Code
Here, we simply generate different QR codes which will store some data and display it to the user’s browser. Let’s create a new file and add the below code to create a QR code that stores simple text in it.
<?php
require_once("phpqrcode/qrlib.php");
$data = "123456789";
QRcode::png($data);
?>
So whenever a user visits this webpage it will create a QR code from a given text and display it to the user’s browser.
Here, we can also store generated QR codes into an image file and available it user for downloading. Let’s take another example where we’ll create a .png file of the QR code.
<?php
include 'phpqrcode/qrlib.php';
$text = "John Wick";
$file = 'images/'.uniqid().".png";
$ecc = 'L';
$pixel_Size = 10;
$frame_Size = 10;
// Generates QR Code and Stores it in directory given
QRcode::png($text, $file, $ecc, $pixel_Size, $frame_size);
// Displaying the stored QR code from directory
echo "<center><img src='".$file."'></center>";
?>
First of all, we will create the filename and content for the QR code. We have also set the pixel size and frame size for the QR code. At last, we have created a QR code and displayed it as an image to the user. Whenever a user runs this script it will create a new PNG file to our server and display it to the user.
Conclusion
In this article, we have taken some examples that demonstrate you to create QR codes using PHP with the PHP QR code library. There are many libraries available to perform the same task. You can use those libraries as per your requirements.