How to Create QR Code with Google API and PHP



QR code stands for Quick Response code. It is a two dimensional code designed to capture all the information using a Smart Phone. It is a type of matrix bar-code. They are also known as hardlinks or physical world hyperlinks. This code can be used to encode any information such as text, URL, Telephone numbers, Addresses and any other data. Here I will discuss how to create QR code with google API and php.

Google Chart API allows us to create QR code for our desired data and it is absolutely free.
Root URL: https://chart.googleapis.com/chart?

It needs three required parameters. These parameters are as follows:

chs=’width x height’ – This defines the size of the image returned in pixels and the format should be ‘width x height’.
cht=qr – This defines the type of the image to be returned. It should be set to qr for QR code.
chl – This specifies the data to be encoded. Data can be digits (0-9), alphanumeric characters, binary bytes of data.

Now I have create a function to call the google api to generate the QR code with user input variable $content.

function getQRCode($content, $size = 200) {
    $google_api = "http://chart.apis.google.com/chart?";				
    return $google_api.'chs=' . $size . 'x' . $size . '&cht=qr&chl=' . urlencode($content);
}

To get he input from the user need to create a form like as below:

<form name="content" method="post">
    <table width="100%">
        <tr>
	    <td>Enter Your Text</td>
	    <td><input type="text" name="content" value="" /></td>
	</tr>
			
	<tr>
	    <td></td>
	    <td><input type="submit" value="Create" name="submit" /></td>
	</tr>
    </table>
</form>

Now need to get the value of user and pass it to the function getQRCode to get the qr code image. We will do this as below:

<?php if(isset($_POST['content']) && $_POST['content']){ ?>
	<div style="border:#ccc solid 8px; width:650px;padding:5px;">
		<img src="<?php echo getQRCode(trim($_POST['content'])); ?>" />
	</div>
<?php } ?>

Now, get your smartphone and try to scan this QR code. If you enter the url you will be redirected to that url.

Live Demo

QR Code with Google API and PHP
QR Code with Google API and PHP