Skip to main content

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();

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
  3. thanks for the information. I never knew about qr code. ivanka hot

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...

Resize Image While Uploading with PHP

On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.