Generate QR Code with Google API and PHP

QR (Quick Response) was invented about 20 years ago by A Japanese company named Denso Wave. Nowadays QR is one of the most popular 2D barcode format. It is designed to store text characters like URLs, Telephone numbers, Addresses and whatever else. The good thing of QR barcode is that it can be read by mobile phone devices.

Though it is very difficult to generate QR code by using PHP but thanks to Google because its has a nice API for generating QR codes. We can make QR codes very easily by using Google Chart API and it is absolutely free!.

In this post I am going to show you two ways to generate QR code with php. First one is a simple function that returns Google Chart's direct link and second one is little bit advanced and tricky.

Live Demo Download Source

The Simple QR Link Generator Function

This function generates Google Chats API URL for QR code image.

/**
 * QR Code Link Generator
 * 
 * @param string $data
 * @param int $width & $height (optional)
 * @param str $charset ('optional')
 * @param string $error ('optional') L | M | Q | H
 */
function qr($data, $width = 200, $height = 200, $charset = 'utf-8', $error = 'H')
{
  // Google chart api url
  $uri = 'https://chart.googleapis.com/chart?';

  // url queries
  $query = array(
    'cht' => 'qr',
    'chs' => $width .'x'. $height,
    'choe' => $charset,
    'chld' => $error,
    'chl' => $data
  );

  // full url
  $uri = $uri .= http_build_query($query);

  return $uri;
}

Usage

<img src="<?php echo qr('http://www.w3bees.com', 400, 200) ?>">


Advanced QR Code Generator

This is a little bit tricky way to generate QR code. By using this class you can use your won domain to make QR code. For example

<img src="http://mysite.com/qr.php?data?=www.w3bees.com" />

The another thing of this class is that it supports server caching and it is curl powered.

/**
* QR Code with Google API
*/
class QR
{
  /* Default QR Parameters */
  var $data = '';
  var $width = 200;
  var $height = 200;
  var $charset = 'utf-8';
  var $error = 'H';

  /* Google Chart URI */
  var $apiuri = 'https://chart.googleapis.com/chart?';
  var $query;

  /* Cache Settings */
  var $cache = true;
  var $cacheDir = 'cache/';
  var $cachePath;

  /**
   * __construct
   * @param string $data
   */
  function __construct($data)
  {
    $this->data = $data;
  }

  /**
   * getQR
   * @return void
   */
  function getQR()
  {
    $this->query = $this->query();

    header('Content-type: image/png');

    if ($this->cache) {

      $this->cachePath = $this->cache($this->query);

      /* if cached if exist, simple read cached file */
      if ( file_exists($this->cachePath) ) {
        readfile($this->cachePath);
      }
      else {
        $this->newQR();
      }
    }
    else {
      $this->newQR();
    }
  }

  /**
   * New QR From Google's Server
   */
  function newQR()
  {
    $url = $this->apiuri . $this->query;

    /* download file from google server */
    $data = $this->httpRequest($url);

    $img = imagecreatefromstring($data);

    switch ($this->cache) {
      case true:
        imagepng($img);
        imagepng($img, $this->cachePath);
        break;
      
      default:
        imagepng($img);
        break;
    }

    imagedestroy($img);
  }

  /**
   * config
   * @param array
   */
  function config($args)
  {
    $this->width = isset($args['width']) ? $args['width'] : $this->width;
    $this->height = isset($args['height']) ? $args['height'] : $this->height;
    $this->charset = isset($args['charset']) ? $args['charset'] : $this->charset;
    $this->error = isset($args['error']) ? $args['error'] : $this->error;
  }

  /**
   * query
   * @return string
   */
  function query()
  {
    // url queries
    $query = array(
      'cht' => 'qr',
      'chs' => $this->width .'x'. $this->height,
      'choe' => $this->charset,
      'chld' => $this->error,
      'chl' => $this->data
    );

    // full url
    return http_build_query($query);
  }

  /**
   * Cache Path
   * @return string
   */
  function cache($query)
  {
    if (!file_exists($this->cacheDir))
      @mkdir($this->cacheDir);

    return $this->cacheDir . sha1($query) . '.txt';
  }

  /**
   * curl based http request
   * @param sting $url
   * @return string
   */
  function httpRequest($url)
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);

    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
  }
}


Simple Usage

$qr = new QR('http://www.w3bees.com');
$qr->getQR();

Custom Configuration

$qr = new QR('http://www.w3bees.com');
$qr->config(array('width'=>100, 'height'=>100));
$qr->getQR();

4 comments:

  1. Hi thank you so much for your post. I downloaded your code and i am trying to run it on my localhost on my laptop. i am nt able to get the qrcode!i keep on seeing a broken image. do u have an idea of how i can solve this!

    ReplyDelete
  2. ham gia VÒNG PHỎNG VẤN MIỄN PHÍ và nhận HỌC BỔNG LÊN ĐẾN 100% từ đại diện của 40 trường đại học.
    Đăng ký tham gia Triển lãm vào
    dịch vụ kế toán trọn gói quận gò vấp
    dịch vụ kế toán trọn gói quận 1
    dịch vụ kế toán trọn gói quận 4
    Giờ style sành điệu là đồ vẫn phải đẹp, sang mà vẫn có thể vạch lên cho con ti mà ko bị hở. Hahha.
    Chắc khó mà váy vóc nổ

    ReplyDelete

Go to top