简体   繁体   English

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

[英]Force download remotely hosted images to browser

Suppose I have an image hosted with Google: https://www.google.ae/images/srpr/logo11w.png 假设我有一个托管在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. 这适用于本地托管的图像,而不适用于上面像Google示例一样远程托管的图像。

The very first example on the readfile() manual page is titled 'Forcing a download using readfile()', with a .gif file: 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;
}

Under the Notes section is the following tip: Notes部分下面是以下提示:

A URL can be used as a filename with this function if the fopen wrappers have been enabled. 如果已启用fopen包装器,则URL可用作此函数的文件名。 See fopen() for more details on how to specify the filename. 有关如何指定文件名的更多详细信息,请参阅fopen()。 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'; 因此,如果您只是替换$file = 'https://www.google.ae/images/srpr/logo11w.png'; for $file = 'monkey.gif'; 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.' 但是,正如@charlietfl所写, “你无法控制另一个服务器如何处理请求。” so you can't link directly to the original source and expect the file to download. 所以你不能直接链接到原始源并期望文件下载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM