Wednesday, November 13, 2013

How to Make an Image Downloadable


Create the HTML file to add a link like 'click here to download image'.
code:
<a href="download.php?imgfile=occ.png"><img src="download.png" alt="download image"></a>

Then create the download.php file.Code is given below
<?php
// Force download of image file specified in URL query string and which is in the same directory as this script:
if(!empty($_GET['imgfile']))
{
   $filename = basename($_GET['imgfile']); // don't accept other directories
   $size = @getimagesize($filename);
   $fp = @fopen($filename, "rb");
   if ($size && $fp)
   {
      header("Content-type: {$size['mime']}");
      header("Content-Length: " . filesize($filename));
      header("Content-Disposition: attachment; filename=$filename");
      header('Content-Transfer-Encoding: binary');
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      fpassthru($fp);
      exit;
   }
}
header("HTTP/1.0 404 Not Found");
?>