PHP Generate QR Code using Google Chart API Example

By Hardik Savani May 14, 2024 Category : PHP

I am going to show you example of generate qr code php using google api. step by step explain php generate qr code image. i would like to share with you how to generate qr code in php example. This article will give you simple example of how to generate qr code using php google chart api.

If you need to generate qr code in your php application then you can use google chart api to generate qr code with that. i will give you very simple example of how to generate qr code in php.

Let's see bellow code and you can use it with php application.

Preview:

QRBarCode.php

<?php

/**

* QR_BarCode - Barcode QR Code Image Generator

*

*

*/

class QRBarCode{

/* Google Chart API URL */

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

/* Code data */

private $codeData;

/**

* Write code on Method

*

* @return response()

*/

public function url($url = null){

$this->codeData = preg_match("#^https?\:\/\/#", $url) ? $url : "http://{$url}";

}

/**

* Write code on Method

*

* @return response()

*/

public function text($text){

$this->codeData = $text;

}

/**

* Write code on Method

*

* @return response()

*/

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;

}

}

?>

Generate QR Code

index.php

<?php

/* include QRBarCode class */

include "QRBarCode.php";

$qr = new QRBarCode();

/* create text QR code */

$qr->text('ItSolutionstuff.com');

/* display QR code image */

$qr->qrCode();

Save QR Code

index.php

<?php

/* include QRBarCode class */

include "QRBarCode.php";

$qr = new QRBarCode();

/* qrCode(size, path) */

$qr->qrCode(350, 'images/itsolution-qr.png');

now you can run this index.php file and check it.

i hope it can help you...

Tags :
Shares