QR code with php

Generating and Scanning QRcodes With PHP

In this article i will show how to process QR codes in PHP and how to generate QR code images and scan those images back to their original text.

 

 

Overview

QR codes is a standard that represents some decoded text often used with commercial items such as products and it used to identify those items in graphical format in the form of images. There are a lot of software that can generate and scan QR codes and in this tutorial we will show you how to manipulate QR codes with PHP.

 

For the purpose of this tutorial we will use two libraries that can be used to generate and scan QR codes, which are:

  • phpqrcode: we will use this to generate QR codes, you can download it from this link.
  • php-qrcode-detector-decoder: we will use to scan QR codes install it from this link.

After downloading the two libraries add them to your project, in the next sections we will see how to generate QR codes.

 

Generating QR codes:

To generate QR codes you need first to include the qrlib.php in your project, next create a new file generate.php as shown below:

 

Output QR codes to the browser:

To output QR codes to the browser directly call Qrcode::png() as shown:

Now run your script in the browser, and check the image shown.

 

Passing the output to img src:

Instead of outputting the result directly into the browser you can use the it as the src of the img tag as shown here:

Output QR code according to parameter:

You can pass parameters to the url therapy you can capture those parameters and output QR codes accordingly as shown below:

Also you can pass parameters to url in the img src:

 

Saving the Qr code to a file:

You can if you want to save the QR code to file or store it in the database, just pass a second parameter to QRcode::png() which is the file path to store in the png as shown here:

 

Controlling pixel size:

You can control the pixel size when creating the QR code by passing a third and fourth parameters, the third parameter represents the ECC level and the fourth parameter represents the pixel size, 1 small size and 4 biggest size:

Reading QR codes:

To read or scan Qr code we will use the second library, so include the dependencies from the vendor autoload file as follows:

As shown above we included the vendor composer file and then we imported the namespace relating the class QrReader, not that without this line you will get a fatal error.

To read specific Qr codes just pass the image png file to read method as shown below:

Calling $qrcode->text() will retrieve the QR code data.

 

Share this: