Knowing how to generate QR code in PHP and allow users to download it as an image is an essential skill for developers. QR codes play a major role in industries like online payments, eCommerce, ticket booking, and even on visiting cards.
A QR code stores information such as serial numbers or website addresses. When someone scans it, they can access this data. QR codes are two-dimensional barcodes that mobile phones or scanners can read easily.
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.
For creating unique identifiers or passwords, PHP offers easy ways to generate random strings.