允许用户使用 PHP 下载外部图像


Allow user to download external image using PHP

我设置了它,以便用户可以通过单击按钮下载图像(如果它托管在我的网站上),但它不适用于外部图像。是否可以使用外部图像(使用 URL)执行此操作,而无需先将其复制到服务器上的文件夹中?

这是我在自己网站上用于图像的内容。

$str = $_GET['image'];
$img_name = substr(strrchr($str, '/'), 1);
$image = "../u/i/".$img_name;
if (file_exists($image)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($image));
    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($image));
    ob_clean();
    flush();
    readfile($image);
    exit();
}

正如您在 http://php.net/manual/en/function.readfile.php 上看到的,您可以使用外部URL。

如果启用了 fopen 包装器,则 URL 可以用作此函数的文件名。请参阅 fopen() 了解有关如何 指定文件名。请参阅支持的协议和包装器 链接到有关各种包装器具有哪些功能的信息, 有关其用法的说明,以及有关它们的任何预定义变量的信息 可以提供。

这是一个PHP设置:http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

(代码不需要更改。