How to generate a QR code for a website

How to generate a QR code for a website

In this short article, we’ll take a look at one way to generate a QR code using PHP.
According to the “brain” of our internet (Wikipedia), which rarely lies :), a QR code is:

QR code (Quick Response Code) — a trademark for a type of matrix barcode (or two-dimensional barcode), originally developed for the automotive industry in Japan.

To put it simply, a QR code is an image containing a square-shaped barcode. It can be scanned using a mobile phone (with the proper software installed) or a special scanning device.

Let’s get to the point

We won’t reinvent the wheel — to generate a QR code in PHP, we’ll use the ready-made library “phpqrcode” (thanks to the author!). The library can be downloaded from GitHub via this link.

The library is lightweight and consists of just a few dozen files totaling a little over 250 KB.

How to use the phpqrcode library

Unzip the downloaded library on your server. The archive includes an index.php file as a working example. If you want, you can play around with QR code size and ECC level (which, as I understand, determines the quality).

The library allows you to create QR codes in several formats:

  • png
  • svg
  • eps
  • as plain text

As an example, let’s walk through generating a PNG image of a QR code. There are two common approaches:

  1. Display the result directly in the browser (useful for generating a QR code via link)
  2. Save the generated image to a directory

For both cases, the following code is used:

QRcode::png($text, $outfile, $level, $size, $margin, $saveandprint, $back_color, $fore_color);

Where:
$text — the text to encode into the QR code
$outfile — the directory where generated barcodes will be saved (if set to false, the code is displayed directly in the browser as a regular image)
$level — error correction level
$size — size of the QR code
$margin — margin around the image
$saveandprint — if set to false, the “Content-type: image/png” header is not sent
$back_color — background color
$fore_color — foreground (dot) color

That’s all. Thanks!

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *