Force apache to download an image instead of opening it

Have you ever came across a situation where you wanted an image to download instead of having the browser to display it? This is how you can do it . Enter the following code in a php file foo.php and call it like foo.php?file=myimage.jpg. Then a browser save dialog box will appear.

PHP:
  1. if(!$_GET['file']){exit;}
  2. $file = basename($_GET['file']);
  3. header("Content-Length: " . filesize($file));
  4. header('Content-Type: image/jpg');
  5. header('Content-Disposition: attachment; filename='.$file);
  6. readfile($file);

If you want to do the same with other kind of files like video etc, just replace the 'image/jpg' above with on of the following:

"pdf": "application/pdf"
"exe": "application/octet-stream"
"zip": "application/zip"
"xls": "application/vnd.ms-excel"
"ppt": "application/vnd.ms-powerpoint"
"gif": "image/gif"
"png": "image/png"
"jpg": "image/jpg"
"mp3": "audio/mpeg"
"mp3": "audio/mp3"
"wav": "audio/x-wav"
"mpe": "video/mpeg"
"mov": "video/quicktime"
"avi": "video/x-msvideo"

Leave a Reply

You must be logged in to post a comment.