How to Generate QR Code in PHP

Subodh Poudel Feb 02, 2024
How to Generate QR Code in PHP

This article will introduce a few methods to generate QR codes in PHP.

Use the Google QR Code API to Generate QR Code in PHP

We can use the QR code to store information like URLs, wifi passwords, contact information, etc. This information is represented in alphanumeric characters in the QR code.

As QR code exists in two-dimension, we often see it in the screen and hard copy format. We can use mobile devices to scan the QR code.

Generation of QR codes is not as difficult as it seems. Google provides an API that makes the generation of QR codes very easy.

We can create a QR Code with a GET request directly from the URL. The base URL for QR code generation is shown below.

https://chart.googleapis.com/chart?

Let’s go through the other query parameters that define the QR code.

  1. cht=qr: It defines the chart to be created as a QR code. It is a required query parameter.

  2. chs=widthxheight: chs defines the size of the QR code in terms of height and width. It is also a required query parameter.

  3. chl=data: chl defines the data the QR code represents. It is also a required query parameter.

    For example, the URL should be defined here if we have to generate a QR code for a URL.

  4. choe=encoding: It defines the encoding of the data in the QR code. It is an optional query parameter.

Let’s look at the example below to create a QR code redirecting the user to YouTube.

https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=https%3A%2F%2Fwww.youtube.com&choe=UTF-8

Here, the size of the QR code is 300x300, defined in the chs parameter. The symbol & is used to separate the queries in the URL.

The query parameter cht=qr indicates the chart is a QR code. For the data, we have written https%3A%2F%2Fwww.youtube.com for the value of the chl parameter.

Let’s break down the value below.

We have used a few escape characters to represent some characters in the URL above. These are:

  1. %3A: It represents :.
  2. %2F: It represents /.

The data is translated to https://www.youtube.com/.

We have used the UTF-8 encoding. We can use the above URL in the img HTML tag to create a QR code in a PHP application.

Code Example:

<img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=https%3A%2F%2Fwww.youtube.com&choe=UTF-8" />

As a result, a QR code appears on the webpage. When the QR code is scanned, it will redirect to YouTube.

In this way, we can generate QR codes in PHP.

Subodh Poudel avatar Subodh Poudel avatar

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

LinkedIn