0

I have in my index.php a link like this:

<a href="download.php?url=http://example.com/image.jpg">Download</a>

I need that when you click that link the download dialong opens to save the foto with a specific name like myfile123.jpg.

In my download.php I have this:

header('Content-type:image/jpeg');

$handle = fopen($_GET['url'], "rb");
while (!feof($handle)) {
  echo fread($handle, 8192);
}
fclose($handle);

And while it retrieves the image, it just opens it in the same tab (instead of forcing the dialog).

nick
  • 2,819
  • 5
  • 33
  • 69

2 Answers2

3

Take a look on the PHP readfile example

Example from php.net:

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
Michael
  • 556
  • 2
  • 8
  • Deleted my previous comment saying it worked, it has a problem. While it forces the download dialog, when I download the image it is empty... – nick Jun 05 '18 at 15:41
  • Check also the path and if the file exists – Michael Jun 05 '18 at 16:10
1

You need to add another header, in order to trigger the download, like:

header('Content-Disposition: attachment; filename="image.jpg"');

More info about the Content-Disposition header, here: https://developer.mozilla.org/es/docs/Web/HTTP/Headers/Content-Disposition

Hackerman
  • 12,139
  • 2
  • 34
  • 45