Generate QR code in php using google api

Generate QR code in php using google api

The QR code (Quick Response Code) is the trademark for a type of matrix barcode. A QR code is a machine-readable code consisting of an array of black and white squares. Normally we can say that QR code is the way to store the information in an image format. QR code first designed in 1994 for the automotive industry in Japan. These image information for reading from the camera on a smartphone.

QR code contains a large amount of information in a single image, but people can not read in this image. This information only can be readable by the machine. In this tutorial, we'll discuss the Google Chart API. This Google API helps to create a QR code easily. We can use this Google Chart API:

$googleChartAPI = 'http://chart.apis.google.com/chart';

Call above Google API using cURL method in PHP. cURL is a library that lets you make HTTP requests in PHP. In the post filed some parameter are required by the API. Parameter cht=qr is Required for Specifies a QR code, Parameter chs=<width>x<height> is Required for Image size, and Parameter chl=<data> is Required for the data to encode. Data can be digits (0-9), alphanumeric characters, binary bytes of data, or Kanji. You cannot mix data types within a QR code. The data must be UTF-8 URL-encoded.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->googleChartAPI);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "chs={$size}x{$size}&cht=qr&chl=" . urlencode($this->codeData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$img = curl_exec($ch);
curl_close($ch);

Create a class file for creating the QR code image in png format, this class contain the multiple methods to create your QR code image. After using this QR code class, simply call the relevant method and pass the information which is required by the method and then create your QR image:

/**
 * QR_BarCode - Barcode QR Code Image Generator
 * @author Legend Blogs
 * @url http://www.legendblogs.com
 */
class QR_BarCode{
    
    // Google Chart API URL
    private $googleChartAPI = 'http://chart.apis.google.com/chart';
    // Code data
    private $codeData;
    
    /**
     * URL QR code
     * @param string $url
     */
    public function url($url = null){
        $this->codeData = preg_match("#^https?\:\/\/#", $url) ? $url : "http://{$url}";
    }
    
    /**
     * Text QR code
     * @param string $text
     */
    public function text($text){
        $this->codeData = $text;
    }
    
    /**
     * Info QR code
     * @param string $name
     * @param string $email
     */
    public function info($name, $email){
        $this->codeData = "NAME:{$name};MATMSG:TO:{$email};";
    }
    
    /**
     * Email address QR code
     * @param string $email
     * @param string $subject
     * @param string $message
     */
    public function email($email = null, $subject = null, $message = null) {
        $this->codeData = "MATMSG:TO:{$email};SUB:{$subject};BODY:{$message};;";
    }
    
    /**
     * Phone QR code
     * @param string $phone
     */
    public function phone($phone){
        $this->codeData = "TEL:{$phone}";
    }
    
    /**
     * SMS QR code
     * @param string $phone
     * @param string $text
     */
    public function sms($phone = null, $msg = null) {
        $this->codeData = "SMSTO:{$phone}:{$msg}";
    }
    
    /**
     * VCARD QR code
     * @param string $name
     * @param string $address
     * @param string $phone
     * @param string $email
     */
    public function contact($name = null, $address = null, $phone = null, $email = null) {
        $this->codeData = "MECARD:N:{$name};ADR:{$address};TEL:{$phone};EMAIL:{$email};;";
    }
    
    /**
     * Content (gif, jpg, png, etc.) QR code
     * @param string $type
     * @param string $size
     * @param string $content
     */
    public function content($type = null, $size = null, $content = null) {
        $this->codeData = "CNTS:TYPE:{$type};LNG:{$size};BODY:{$content};;";
    }
    
    /**
     * Generate QR code image
     * @param int $size
     * @param string $filename
     * @return bool
     */
    public function qrCode($size = 200, $filename = null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->googleChartAPI);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "chs={$size}x{$size}&cht=qr&chl=" . urlencode($this->codeData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $img = curl_exec($ch);
        curl_close($ch);
    
        if($img) {
            if($filename) {
                if(!preg_match("#\.png$#i", $filename)) {
                    $filename .= ".png";
                }
                
                return file_put_contents($filename, $img);
            } else {
                header("Content-type: image/png");
                print $img;
                return true;
            }
        }
        return false;
    }
}

Include this class file in your project file and create an object to make your QR code image:

Loading...
include('QR_BarCode.php');
$qr = new QR_BarCode()

Now create your project file to use this class. Let's take an example with this file:

<!DOCTYPE html>
<?php
//include QR-Code generator file
include('QR_BarCode.php');
//Object for QR Code
$qr = new QR_BarCode()
        
?>
<html lang="en">
    <head>
        <title>QR-Code Generating Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container">
            <h2 class="text-danger">QR-Code Generating Example</h2>
            <form method="post">
                <div class="form-group">
                  <label for="Name">Name</label>
                  <input type="text" placeholder="Name" class="form-control" name="name" required="">
                </div>
                <div class="form-group">
                  <label for="Email">Email address</label>
                  <input type="email" placeholder="Email" class="form-control" name="email" required="">
                </div>
              <div class="statusMsg"></div>
              <input type="submit" name="submit" class="btn btn-danger" value="Submit"/>
          </form>
            <div>
                <?php
                if(isset($_POST['submit'])){
                    $name = $_POST['name'];
                    $email = $_POST['email'];
                    
                    //create text QR code
                    $qr->info($name, $email);
                    //Save QR in image
                    $qr->qrCode(400,'qr-legendblogs.png');
                }
                //Display QR
                ?>
                <img src="qr-legendblogs.png" alt="qr-legendblogs" />
            </div>
        </div>
    </body>
</html>

Output:

QR image

Download source code:

Generate QR code in PHP using Google API

Related posts

Write a comment