views:

1197

answers:

3

Hello everybody! How do you actually download a picture when you click on it? Is there some kind of a javascript code to do just that? Here is how i show the image with pure HTML.

<a href="#"><img src="myPic.png" border="0"></a>
A: 

Do you want to open the picture in a new window/tab? Or do you want to download it to the users computer? If you want the user to save the image, then you need to set the content-type of the file they receive:

<?php
$file = $_GET['file'];

header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary"); 
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
?>

Remember to check the input so people can't download source files.

Marius
No, you don't. Use accurate content types and content-disposition headers. Also, when writing examples with gaping security holes in them — provide more prominent warnings about those security holes.
David Dorward
A: 

Assuming by "download" you mean "Cause the user's browser to throw up the 'save or open' dialogue" — you can't.

You could link to another URL offering the same file but with the Content-Disposition header set to attachment. The specifics of how you would provide such a resource at that URL would depend on the server side capabilities on offer to you.

David Dorward
+1  A: 

Most people right-click on the image and choose "Save image as..."

The alternate is to link to use a server-side script that sets a "Content-type" and "Content-disposition" header. In PHP, that would be something like this example from the docs:

header('Content-Type: image/png'); // or 'image/jpg' or 'image/gif'
header('Content-Disposition: attachment; filename="filename.png"');
readfile('original.png');

UPDATE: Since you say the image is generated by a PHP script in the first place, there are a few options:

  • Put the URL (sig.php?...) as the parameter to readfile. This will mean double processing for anyone who clicks to download.
  • Cache the output from your image generation script to the filesystem, then pass that file to readfile.
  • Edit the image generation script to accept an extra parameter like mode=download and then where you are about to output the image, if the parameter is present, set those two headers above.
DisgruntledGoat
You replace the readfile line with your existing code for generating the image…
David Dorward
I updated the answer with suggestions for your additional question.
DisgruntledGoat