强制将远程托管的图像下载到浏览器


Force download remotely hosted images to browser

假设我有一个由谷歌托管的图像:https://www.google.ae/images/srpr/logo11w.png

我想下载这个图像文件,而不是直接在浏览器中打开。

我试过:

<?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");
?>

这只适用于本地托管的图像,而不适用于像上面的谷歌示例那样远程托管的图像。

readfile()手册页面上的第一个示例标题为"使用readfile(()强制下载",其中包含一个.gif文件:

$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;
}

Notes部分下面是以下提示:

如果启用了fopen包装器,则URL可以用作此函数的文件名。有关如何指定文件名的更多详细信息,请参阅fopen()。请参阅支持的协议和包装器,以获取有关各种包装器的功能、使用说明以及它们可能提供的任何预定义变量的信息的链接。

因此,如果您简单地用$file = 'https://www.google.ae/images/srpr/logo11w.png';代替$file = 'monkey.gif';,那么上面的脚本应该会强制下载图像。

当然,这种方法的最大缺点是图像首先传输到服务器,然后下载到客户端。但是,正如@charlietfl所写,"你无法控制另一台服务器如何处理请求。"因此,您不能直接链接到原始源并期望下载该文件。