•Try•
Catch

Force Download Image

Use PHP to serve an image as an attachment

If you find yourself in the unlikely scenario of not being able to use .htaccess to do something like this, you may find yourself in the even less likely scenario of needing this snippet.

Pass in a file path as a URL parameter or alter how $file is set to fit your needs and this snippet will ensure the image is downloaded as an attachment.

Note that to accomplish this same thing in supported HTML5 browsers, all you need to use is the HTML5 Download attribute.

// get the file file from a URL parameter (for example)
$file = $_GET['fp'];
$file = urldecode($file); 

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . 'myimage.png' . '"'); 
header('Content-Transfer-Encoding: binary');
header("Last-Modified: " . date( "D, j M Y H:i:s", strtotime("- 1 month")));
header("Expires: Thu, 20 Sep 2012 05:00:00 GMT");
header("Cache-Control: max-age=2692000, public"); 
header("Pragma: cache"); 
ob_clean();
flush();
readfile($file);
exit;

Comments (3)

  1. mindeffects:
    Nov 18, 2012 at 02:33 AM

    I used this method with video files, but with large files and slow lines you run into time-out problems using readfile, because the script runs as long as the download takes. Or finishes unfinished, which kinda sucks. ;-)
    So the htaccess/direct-link method is less fun but more robust. Maybe you could ad it to your post.
    cheers, Oliver

  2. JP DeVries:
    Nov 18, 2012 at 02:52 AM

    Ya it's definitely got some drawbacks. There's an htaccess trick here http://www.givegoodweb.com/post/30/forcing-a-download-with-apache-and-htaccess

  3. Blue Monkey:
    Nov 18, 2012 at 06:40 AM

    Nice. I've always used the .htaccess method. I come here and learn two new ways to do it. Very cool.


Add a Comment





Allowed tags: <b><i><br>Comment:


** Time spent on this website is non-refundable **

modmore