Home > Software engineering >  PHP how to save qr code generated in api.qrserver.com/v1/create-qr-code
PHP how to save qr code generated in api.qrserver.com/v1/create-qr-code

Time:03-19

I have been generated a qrcode in my php script and the output tag is something like this:

<img src="http://api.qrserver.com/v1/create-qr-code/?data=http://example.com/url321&amp;size=256x256&amp;color=000000&amp;bgcolor=ffffff&amp;margin=1px" alt="Scan QR-Code" title="Scan QR-Code" width="256px" height="256px">

Now, I want to save this generated image on my host How can I do this with PHP?

I tried this code but no success:

//This line generates qr code:
$qrsrc = 'http://api.qrserver.com/v1/create-qr-code/?data='.$url.'&amp;size='.$size.'&amp;color='.$color.'&amp;bgcolor='.$bgcolor;

//And the following lines try to store it:
$image_name = 'test.png';
$save_path = 'files/qrcode/'.$image_name;
$image_file = fopen($save_path, 'wb');
fwrite($image_file, $qrsrc);
fclose($image_file);

This code creates the image file. but image is not correct file... Thank you.

CodePudding user response:

You're not actually fetching the image. You're just storing the literal URL as text in your test.png file.

First fetch the image:

$qrsrc = 'http://api.qrserver.com/v1/create-qr-code/?data='.$url.'&amp;size='.$size.'&amp;color='.$color.'&amp;bgcolor='.$bgcolor;
// Get the image and store it in a variable
$image = file_get_contents($qpsrc);   

// Save the file
$image_name = 'test.png';
$save_path = 'files/qrcode/'.$image_name;

// Save the image
file_put_contents($save_path, $image);

Note: To be able to fetch URL's using file_get_contents(), you need to make sure that you have allow_url_fopen enabled. Most installs I've used does already have it enabled as default.
You can read more about it in the manual

  • Related