Skip to content

Generate QR Code in PHP: Complete API Tutorial

Generate QR Code in PHP: Complete API Tutorial

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.

Planning the QR Code Payload

Keep the encoded value useful

A QR image is only as useful as the information behind it. Before writing code, decide whether the scanner should open a page, show a message, start a phone call, compose an email, or import contact information. Each purpose benefits from a predictable payload format.

For a product label, a short HTTPS address is usually easier to scan than the full product description. The page at that address can contain the changing details, while the printed QR image remains unchanged. For a temporary campaign, include a server-side identifier so you can measure which printed version was used without putting private information into the code itself.

PHP QR code generation workflow infographic
PHP QR Code Workflow

Choose an appropriate image size

The chs value controls the requested image dimensions, but it does not replace good layout decisions. A code printed on a poster needs more physical space than one displayed inside a mobile application. Leave a clear margin around the modules and avoid placing text, logos, or borders over the quiet area.

Test the actual output at the size and distance where people will scan it. A code that works on a developer's monitor may fail after being printed, compressed by a messaging service, or viewed in low light. Keep contrast strong and avoid changing the dark modules to a pale colour.

Decide whether the request is synchronous

For a single form submission, a synchronous cURL request is simple: submit the payload, wait for the image, and show the result. If an application generates thousands of codes, move the work into a queue or background job. That prevents a slow image provider from holding a web request open and lets you retry failures without asking the visitor to submit the form again.

  • Use a short timeout for normal browser requests.
  • Log the provider response and request identifier on the server.
  • Retry only errors that are temporary, not invalid payloads.
  • Keep the original payload so an image can be regenerated later.

Building a Form for Text and Contact Data

Separate display fields from the payload

A form may ask for a person's name and email address, but the QR payload should be assembled by server-side code. Do not accept a hidden field containing an arbitrary file path or provider URL. Read the expected fields, validate them, and create the encoded value from trusted application rules.

Handle failed submissions clearly

When generation fails, show a useful validation message rather than a blank image. Network failures should be logged for the administrator, while an invalid email or empty name should be returned to the form. This distinction helps users correct their input and helps developers diagnose infrastructure problems.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim((string)($_POST['name'] ?? ''));
    $email = trim((string)($_POST['email'] ?? ''));

    if ($name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Enter a name and a valid email address.';
    } else {
        $qr->email($email, 'Contact request', 'Hello ' . $name);
        $image = $qr->image(400);
    }
}

Testing and Maintaining the Generator

Test different payloads

Create tests for short text, spaces, punctuation, Unicode characters, long URLs, email addresses, phone numbers, and an empty value. Scan each generated image and compare the decoded value with the original payload. This catches encoding mistakes that are not visible when looking at the image.

Plan for provider changes

Keep the endpoint and request construction inside one class. If the provider changes, you can replace that adapter without rewriting the form, database code, or pages that display the image. Document the provider's request format and review it before using the generator for a new project.

Review the generated image in production

Development success is not enough. Confirm that the saved file has the expected MIME type, that the web server can read it, and that the browser receives the correct image header. If a cache is involved, use a versioned or unique URL when regenerating an image so an older file is not displayed.

Finally, decide how long generated files should remain available. A scheduled cleanup task can remove temporary images, while permanent assets should be tied to a record in your application. This keeps storage predictable and reduces the chance of leaving personal data accessible longer than necessary.

$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:

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

Write a comment