user3800108
user3800108

Reputation: 1248

Force download remotely hosted images to browser

Suppose I have an image hosted with Google: https://www.google.ae/images/srpr/logo11w.png

I want to make this image file download instead of opening directly in the browser.

I have tried:

<?php
function downloadFile($file, $type)
{
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: $type");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
readfile($file);
}
downloadFile("img.jpg", "image/jpg");
?>

This works but only for locally hosted imges, not for images hosted remotely like the Google example, above.

Upvotes: 1

Views: 362

Answers (1)

timclutton
timclutton

Reputation: 13004

The very first example on the readfile() manual page is titled 'Forcing a download using readfile()', with a .gif file:

$file = 'monkey.gif';

if (file_exists($file)) {
    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);
    exit;
}

Under the Notes section is the following tip:

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

So if you simply substitute $file = 'https://www.google.ae/images/srpr/logo11w.png'; for $file = 'monkey.gif'; the above script should force the image download.

Of course, the big drawback with this approach is that the image is transferred to your server first, and then downloaded to the client. But, as @charlietfl wrote 'you can't control how another server handles requests.' so you can't link directly to the original source and expect the file to download.

Upvotes: 3

Related Questions