使用 PHP 创建 .jpg 文件的下载链接

2024-04-20

我想这应该很容易。我有一个分页图像库,每个图像下方都有一个小链接,上面写着“下载 Comp”。这应该允许人们快速将 .jpg 文件(带有 PHP 生成的水印)下载到他们的计算机上。

现在,我知道我可以直接链接到 .jpg 文件,但这需要用户在新窗口中打开图像,右键单击,另存为...等。相反,我想要“下载 Comp”立即启动文件下载的链接。

PHP.net 似乎建议使用 readfile(),因此每个“下载 Comp”链接都会被回显为“?download=true&g={$gallery}&i={$image}”。

然后在页面顶部查看 $_GET['download'] var 是否已设置,如果是,则运行以下代码:

if(isset($_GET['download'])) {
$gallery = $_GET['g'];
$image = $_GET['i'];
$file = "../watermark.php?src={$gallery}/images/{$image}";
header('Content-Description: File Transfer');
    header('Content-Type: application/jpeg');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: public');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
readfile($file);

}

该链接需要很长时间,然后会弹出一个对话框提示,要求您打开或保存文件,但是一旦您保存并尝试打开它,它会说文件已损坏并且无法打开。

有任何想法吗?


不要将 $file 设置为相对 url。 readfile 函数将尝试访问服务器上的 php 文件。那不是你想要的。在您的情况下,watermark.php 文件看起来会发送您想要的内容,因此您可以只设置它所需的环境并将其包含在内。

<?php
if(isset($_GET['download'])) {
    $gallery = $_GET['g'];
    $image = $_GET['i'];
    $_GET['src'] = "{$gallery}/images/{$image}";

    header('Content-Description: File Transfer');
    header('Content-Type: image/jpeg');
    header('Content-Disposition: attachment; filename='.basename($image));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: public');
    header('Pragma: public');
    ob_clean();
    include('../watermark.php');
    exit;
}

另一种(更简单)的方法是修改watermark.php。添加查询参数以使其发送正确的标头以强制下载并链接到该标头

<a href="watermark.php?src=filename.jpg&download=true)">...</a>

水印.php:

<?php
if (isset($_GET['download']) && $_GET['download'] == 'true') {
    header('Content-Description: File Transfer');
    header('Content-Type: image/jpeg');
    header('Content-Disposition: attachment; filename='.basename($src));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: public');
    header('Pragma: public');
}
// continue with the rest of the file as-is

另外,您不需要调用flush()。此时不应发送任何输出,因此没有必要。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 PHP 创建 .jpg 文件的下载链接 的相关文章

随机推荐