4

When I use this code to download this image (only used for testing purposes), I open the downloaded image, and all it gives me is an error. i tried it in chrome. opening it with windows photo viewer, it says that it can't display the picture because it is empty??? here is the code:

<?PHP
 // Define the path to file
 $file = 'http://www.media.lonelyplanet.com/lpi/12553/12553-11/469x264.jpg';

 if(!file)
 {
     // File doesn't exist, output error
     die('file not found');
 }
 else
 {
     header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
 }
 ?>
nwalke
  • 3,170
  • 6
  • 35
  • 60
droidus
  • 613
  • 5
  • 14
  • 25

4 Answers4

4

I've had a chance to work it out. Your problem is two-fold.

First, remove the www. from the url.

Second, remove the call to filesize($file) which is throwing an error because PHP doesn't know the size of the file before it downloads the file. (really, just remove the whole line)

Removing these two things, I was successful.

Umbrella
  • 4,733
  • 2
  • 22
  • 31
2

Replace ob_clean() with ob_end_clean()

You're still buffering, so none of the image contents get to the browser.

Umbrella
  • 4,733
  • 2
  • 22
  • 31
1

If your intention is just the download the file from a third party on click of a link, you could use the new property download in the anchor tag.

The code will look something like

<a download href="path/to/the/download/file"> Clicking on this link will force download the file</a>

It works on firefox and chrome latest version. Should I mention that I didn't check it in IE? :P

Gokul N K
  • 2,428
  • 2
  • 32
  • 40
1

Replace:

ob_clean();
flush();
readfile($file);

With:

echo file_get_contents($file);
Anoop Naik
  • 335
  • 7
  • 15
iambriansreed
  • 21,935
  • 6
  • 63
  • 79