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

问题描述 投票:1回答:1

我进行了设置,以便用户可以通过单击按钮下载图像(如果该图像托管在我的网站上,但不适用于外部图像)。是否可以使用外部图像(使用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();
}
php image file download transfer
1个回答
1
投票

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

如果启用了fopen wrappers,则URL可以用作带有此功能的文件名。有关如何操作的更多详细信息,请参见fopen()。指定文件名。参见Supported Protocols and Wrappers链接到有关各种包装程序具有哪些功能的信息,有关其用法的注释,以及有关任何预定义变量的信息可以提供。

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

(然后不需要更改代码。)

© www.soinside.com 2019 - 2024. All rights reserved.