Generate QR Codes in PHP

Share this article

Used widely in various recent applications, QR Codes can be seen on cola cans, business cards, in sushi bars, and in museums. QR Code is a 2-dimensional barcode specification that was invented in Japan. It is patented. but it’s inventor, Denso Wave, chose not to exercise it and left the standard open for the benefit of all. The code has since grown in popularity because of its ability to include a lot of data in a single image and the proliferation of smartphones with scanning apps. In this article I’ll show you how you can easily generate QR Codes from within your PHP application and share some ideas on how and when to use them, We’ll be using PHP QR Code, a library written in PHP for generating QR Codes and which doesn’t require any dependencies beyond the standard GD2 graphics extension for creating images.

Generating your First QR Code

Start by downloading the latest PHP QR Code library from GitHub. I’ll assume you’ve extracted it successfully and you can go to http://localhost/phpqrcode in your development environment to find the demo version working. You can insert whatever text in the data field you want to be converted to a QR Code image as shown in the screenshot below. If you have any problem getting this to work, make sure you have PHP installed with the GD2 extension, double checking this if necessary using a PHP info page.

Create a new PHP script with the following code:
<?php
include "phpqrcode/qrlib.php";

// create a QR Code with this text and display it
QRcode::png("My First QR Code");
You see how simple it is? With just two lines of code you get a perfectly good QR Code for your application. The opportunities are endless! But wait, this obviously isn’t the full story. The library has more features worth looking at.

Features of the PHP QR Code Library

For a full blown example, try this code:
<?php
QRcode::png("http://www.sitepoint.com", "test.png", "L", 4, 4);
The first parameter specifies the text or data which will be encoded into the image and is passed as a normal string. The second parameter is the name of the output file for the generated PNG image, if any. The default value is a boolean false, in which case the image is flushed to the browser. The third parameter is the level of error correction for the generated barcode, passed as a single letter string. This specifies how much of the data’s codewords (8-bits per codeword) can be restored for a distorted or damaged QR Code image using the Reed-Solomon error correction algorithm. The higher the correction level, the less the data capacity of the barcode can be for a given dimension. Below is a table mapping the levels to their restore percentages and the string constants used when calling the QRcode::png(). (I’ve compiled the table from the Wikipedia article on QR Codes and the method signature in the PHP QR Code library.)

The fourth parameter specifies the size of each of the barcode code squares measured in pixels. Each code square (also named “pixels” or “modules”) is 4×4px. The fifth parameter specifies the white margin boundary around the barcode, measured in code squares (eg. A 16px margin on each side for 4×4px code square). The library supports exporting PNG, SVG, and EPS images, and you can produce QR Codes in any of these formats simply by changing the method name from png() to svg() or eps() and use the correct extension for the generated image’s filename. Also, you can change the background and foreground colors by passing them as additional parameters:
<?php
$backColor = 0xFFFF00;
$foreColor = 0xFF00FF;

// Create a QR Code and export to SVG
QRcode::svg("http://www.sitepoint.com", "test-me.svg", "L", 4, 4, false, $backColor, $foreColor);
The sixth parameter (false in the example above) seems to be a useless parameter. It should be true for saving to a file and exporting to the browser, but it simply didn’t work for me after checking it several times, so keep it false. The library has more features that you can check out if you’d like, for example caching and benchmarking the image generation.

Getting the Size of the Final Bar Code

To get the final size of the image in advance, here’s a simple formula that can use (since the image is a square, we only need to calculate a single dimension and the other will be the same):
Image Size (px) = (Pixels per Module) × (Module Size + 8)
Where as stated earlier, Pixels per Module is specified in the method call as the fourth parameter and the Module Size is selected from these barcode sizing tables as follows:
  1. Select the column of the string type (data bits, numeric, alphanumeric, binary, or Kanji). These specify the maximum data length of such type to be packed in a certain barcode. Earlier I used alphanumeric, but if you are using UTF-8 encoded strings then you may be using the binary type instead. Kanji is for Japanese, but is not tested by the library author.
  2. Choose the desired level of error correction and for your string length find the minimum version number that can handle at least that many characters. The example used 24 or more characters of alphanumeric type at level L, so the value will be version 1 first row.
  3. Get the module for the version you choose, here it will be module 21×21, where the module size will be 21. The PHP QR Code library takes the next version up instead for more room as a safety, so then go up one more.
If you calculate the module size for the version used for the example, you will find that the produced image size should be:
Image Size = 4 × (21 + 8) = 116×116px
But the image generated is 132×132px instead. PHP QR Code took the next version (version 2 instead of version 1, or simply module 25×25), so the actual generated size will be:
Image Size = 4 × (25 + 8) = 132×132px

Common Uses for QR Codes

The most common application for QR Codes is to encode website URLs, such as that to a Facebook fan page of your latest product, your company, etc. The options are endless. I myself use it on my business card and encode the URL to my LinkedIn profile.

QR Codes can also store telephone numbers, vCards, and email addresses. Some sites put them alongside blog articles to act as bookmarks. When it comes to using QR Codes, your only limits are really the data capacity of the code and the space you’ll display it in.

Summary

In this article you’ve seen how to generate QR Codes easily in PHP for various print and web applications. I also showed you how to calculate the final generated image size in advance, since the library doesn’t provide such facility. In short this, working with QR Codes can be enjoyable and open a lot of opportunities. How can you enhance your PHP application with them? Image via Fotolia

Frequently Asked Questions (FAQs) about Generating QR Codes in PHP

How Can I Generate a QR Code with a Specific Size in PHP?

To generate a QR code with a specific size in PHP, you need to adjust the pixel size or scale factor when creating the QR code. For instance, using the PHP QR Code library, you can specify the size as a parameter when calling the png() function. The size parameter determines the width and height of each QR code module in pixels. A larger size will result in a larger QR code.

Can I Generate a QR Code with a Logo in the Middle in PHP?

Yes, you can generate a QR code with a logo in the middle using PHP. This involves generating a standard QR code, loading a logo image, and then combining the two images. The GD library in PHP provides functions for image manipulation, which you can use to accomplish this.

How Can I Change the Color of a QR Code Generated in PHP?

To change the color of a QR code generated in PHP, you can use imagecolorallocate() function from the GD library to set the color for the QR code. You can specify the RGB values for the color you want.

How Can I Generate a QR Code with Error Correction in PHP?

Error correction can be added to a QR code in PHP by specifying the error correction level when generating the QR code. The PHP QR Code library supports four levels of error correction (L, M, Q, H). The higher the error correction level, the more errors can be corrected.

Can I Generate a QR Code that Links to a URL in PHP?

Yes, you can generate a QR code that links to a URL in PHP. When generating the QR code, simply provide the URL as the data to be encoded in the QR code. When scanned, the QR code will direct the user to the specified URL.

How Can I Save a Generated QR Code to a File in PHP?

To save a generated QR code to a file in PHP, you can use the png() function from the PHP QR Code library. This function allows you to specify a filename as a parameter, and the generated QR code will be saved to this file.

Can I Generate a QR Code in a Format Other Than PNG in PHP?

Yes, besides PNG, the PHP QR Code library also supports generating QR codes in other formats such as JPEG and SVG. You can use the jpg() or svg() function instead of png() to generate a QR code in these formats.

How Can I Generate a QR Code with a Specific Version in PHP?

The version of a QR code determines its size. To generate a QR code with a specific version in PHP, you can specify the version as a parameter when generating the QR code. The PHP QR Code library supports versions from 1 to 40.

Can I Generate a QR Code with Alphanumeric Data in PHP?

Yes, you can generate a QR code with alphanumeric data in PHP. The PHP QR Code library supports encoding alphanumeric data in a QR code. Simply provide the alphanumeric data as the data to be encoded when generating the QR code.

How Can I Display a Generated QR Code in a Web Page in PHP?

To display a generated QR code in a web page in PHP, you can generate the QR code as a PNG image and then output it directly to the browser. You can use the png() function from the PHP QR Code library to do this. Make sure to set the correct content type header before outputting the image.

Abdullah AbouzekryAbdullah Abouzekry
View Author

Abdullah Abouzekry is an experienced web-developer with over 7 years developing PHP/MySQL applications ranging from simple web sites to extensive web-based business applications. Although his main experience is with PHP/MySQL and related web technologies, he has developed and localized many desktop applications in C#, Python/Qt, Java, and C++. When not writing code, Abdullah likes to read, listen to oriental music, and have fun with his little family.

Intermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week