David Biga David Biga - 5 months ago 25
PHP Question

Generating QR Code using PHP QrCode

After using the PHP QrCode lib I discovered that for some reason when using a dynamic page with scripts and dialog boxes (JQuery) that when trying to output a QR code in a .png format I get weird symbols instead of the actual generated .png file.

Heres what I have tried:

Created a seperate file with just:

<?php
//include only that one, rest required files will be included from it
include "phpqrcode/qrlib.php";

QRcode::png('barrda554');
?>


Works great,

Attempt 2:

File opened within a dialog box type using JQuery UI:

<?php

header stuff...
include "phpqrcode/qrlib.php";
...
?>
<html>
...
<?php
QRcode::png('barrda554');
?>
..
</html>


In this attempt I get multiple funky symbols for some reason:

�PNG IHDRWWKK/PLTE���U��~�IDAT8��ѱ � P# �c��n :V�L�@�k
y��)�|F��5`ڸzHF|l���
%Z"e�Ы�D{\�ގ����p`�f�eh�������k�[BJeJ�c����,�^�gu�m|Q��o��W����g�
�#�s�<�y��k�m��!v�.��(+�u���$s�-�n$߫>�gR�`IEND�B`�


This has stumped me and I am unsure on how I should approach this to fix it.

Let me know your ideas,

David

UPDATE:

After putting
header('Content-Type: image/png');
within the file that JQuery opens, no cigar.

Here is the actual file:

http://jsfiddle.net/T4nEP/

Answer

The problem is here:

<html>
<?php
QRcode::png('barrda554');
?>
</html>

To understand what this is doing, imagine that you open a regular PNG file in a text editor, and just copy/paste the contents directly into your HTML file. It's not going to show an image - it'll just be garbage, like you're seeing.

To include an image in an HTML file, you need to use the <img> tag, and point to the URL of the image. In this case, the URL of the image would be a PHP script that outputs nothing except the PNG contents - like this:

<img src="qrcode.php">

And then in qrcode.php, generate the image:

<?php
include "phpqrcode/qrlib.php";
QRcode::png('barrda554');
?>

If you need some information from the HTML page in order to generate the image, you can include it as query parameters in the URL, like this:

<img src="qrcode.php?product=1&format=2">

And then get those values in your PHP like this:

<?php
include "phpqrcode/qrlib.php";
$product = $_GET['product'];
$format = $_GET['format']
// ...
// whatever you need to do to generate the proper code
// ...
QRcode::png('barrda554');
?>

And finally - there are ways to include the image data directly into the HTML page, but it's not supported by all browsers, and is not recommended because it makes the page size much larger and prevents the browser from being able to cache the image separately.

You can see more about base64 data URLs here and here.