Generate QR Codes in PHP

Tweet

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://alexfraundorf.com Alex Fraundorf

    Abdullah,
    Thanks for the great article on generating QR codes on the fly. This will certainly come in handy on future projects!

  • Ollie Acheson

    Good article, Abdullah. Thanks.
    Ollie

  • http://orizasahputra.blogspot.com ahmad

    very easy.. great.

  • http://www.carlkay.net John Ghormley

    While I love QR codes, it seems to me that generating them for a screen presentation is much ado about nothing. Why not just post a link to the information being coded in the QR code? Clicking on a live link is much easier and quicker than to scan a QR code with another web enabled device. Presenting a QR code on a smart phone or tablet doesn’t make much sense to me, aside from instructive purposes.

    Now, for printed presentations, QR codes are great! I edit a paper magazine and use them all the time in it’s pages to allow smartphone users to connect electronically with sites, email addresses, and occassionally other information I want to present. I think in this case they help link non-electronic media together with the electronic media.

    I can see how a printed page generated by PHP might benefit by the presence of a QR code, and how that code might need to be dynamic. The benefit comes from the fact that the printed page is not already connected to the Internet. Use of PHP to generate the code at that point might be warranted and even necessary.

    But, to use PHP to generate static information for screen presentation simply makes little sense to me. If the information is static, why not just embed an image of the QR code?

    Thanks for the QR code article and the suggestions for use of QR codes. As a PHP programmer, I even am grateful for the PHP related information.
    John

    • Abdullah Abouzekry

      There are a lot of uses for both applications, screen or printed, for example you can save the QR code on screen on your mobile device and re-use it instead of text url, some like using images more than text :), also you can use it to include identity info of items…etc as a regular barcode. simply the applications for both are up to your imagination only, and I am just showing how you can do this simply in PHP, and apply it as you like.

      Best!

    • Slarti

      My web sites create printable PDF documents… so this is great! Websites can produces much more than HTML documents you know! ;)

      But even ordinary website HTML documents can gain from them if people often make printouts. For an example… it can be quite nice for shops to have QR Code on their product pages, so when a customer is showing them a printout from the web site, the seller can use the QR Code to quickly find the requested product.

  • Anand

    Really good one indeed.

    Please can you tell me how to make it so anyone scan it through their iPhone it jumps to their website ?

    any clue would be much appreciated.

    Thank you,
    Anand

    • Abdullah Abouzekry

      There are a plenty of readers for iPhone which will do this, You can google it and I am sure you will find your best match :)

      Thanks

  • greenmachine

    A good example for presenting the QR code on screen is when you are developing social media sites. For example a person may search a site containing all the local hotels in the region. Adding a QR code with all the business details is invaluable in that the data can then be transferred to the users mobile phone (if they were on desktop or laptop) and then easily transported. QR codes can store pretty much anything. You can create them in a way, that once scanned by the phone, the business details are set as a contact on your phone! That is really cool. They are not primarily for storing website URLs. I’m sure QR codes were invented to replace the old bar code format and originated from factory warehouses where the need to store more data in the product label (for tracking purposes and so on) became a need. I worked with them years ago (generating them with PHP) and it’s nice to see them finally catching on. Thank you very much for your article and presenting this really nice library which is extremely easy to use.

    • Abdullah Abouzekry

      Thank you for the in-depth note, this replies to John Ghormley

      Thanks all

  • http://www.lasane.in/demo/ Kedar

    Just use Google API to generate same.Its Fast

  • DashMug

    The only one function that seem to work for me is when it displays a PNG to the browser. Other formats don’t work. I don’t know why.

    • Abdullah Abouzekry

      Did you use the version mentioned in the article by going to the following link on GitHub??
      https://github.com/t0k4rt/phpqrcode

      It seems you are using another version which doesn’t contain the new functionality.
      Best

  • Happybird

    I think the information about QR Code in this passage is not enough. I do not quite understand QR Code itself.I find this passage: QR Code Introduction. Any one has the same problem with me, take a look at it. it describes in detail.

    • Abdullah Abouzekry

      Thanks for the link, the article is meant for a usage How-To of QR Code not that much details about the structure is needed, but its good to have your link in the comment for further info :)

      Best

  • Shyam

    Good article for generating QR code. However background and foreground color variants did’t work for me. Any help?

  • Arman

    Hi, wandering no one talked about jpg format when it is supported, just no any example about it.

  • http://www.codekites.com Silver Moon

    Barcodes should always be generated as pdf, since they would finally be printed and need to be very accurate on the paper.
    Printing barcodes as images often makes them un readable by barcode readers.

  • http://ninguno javier canon

    excuse me, a question you know if I can decode a QR code to this library or is purely created?

  • Dian

    Hello, please advice, howto generate the QR code from database data, not only one field,

    Thank you
    Dian

  • numeric value in qrcode

    Numeric value doesn’t work in qr code, can you tell me how to add some numeric value in qr code?