Force downloading of a picture in php


If you want to force the browser to download an image directly to hard disk and not show it you have to create a php file with the code below. 

  • You can name it for example download.php
  • Then you can use your script like

http://download.php?id=venezuela+ff&img=018_playa_medina.jpg


download.php


// Force download of image file specified in URL query string and which 
//id is the directory of the gallery
//img is the filename


if(!empty($_GET['img'])&!empty($_GET['id'])) 

   $filename = './galleries/'.$_GET['id'].'/'.$_GET['img'];  //full name


   if(file_exists($filename)) {
   $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=\"".basename($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"); 
?>


The code is altered from a forum post at 
http://www.webdeveloper.com/forum/showthread.php?t=145686

Σχόλια

Δημοφιλείς αναρτήσεις