创建一个下载链接,使用PHP .jpg文件(Creating a download link for

2019-08-18 00:39发布

这应该是容易的,我想。 我有一个分页的图片库,每个图像下面是一个小环节,上面写着“下载小样”。 这应该让人们.jpg文件(用PHP生成水印)快速下载到他们的电脑。

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

PHP.net似乎使用的ReadFile()暗示,所以每个 “下载小样” 链接被呼应为 “?下载=真&G = {$画廊}&I = {$图像}”。

然后,在页面顶部我抓住,看看是否$ _GET [“下载”] VAR isset,如果是这样,我运行下面的代码:

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

}

该链接将一个lonnnnnnnnng时间,然后它带来了一个对话框提示,要求您打开或保存文件,但一旦你保存并尝试打开它,它说,该文件已损坏,无法打开。

有任何想法吗?

Answer 1:

不要$文件设置为相对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>

watermark.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()。 不应该有任何输出在该点发送,所以它是没有必要的。



Answer 2:

header('Content-Type: image/jpeg');

也许?



Answer 3:

这似乎是一个安全问题。

如果有人进入什么:

$g = '../../../../../../';
$i = '../../sensitive file at root';

如何制作的.htaccess(如果你使用的是Apache)我为画廊目录服务的JPEG了作为一个下载,而不是正常的。



Answer 4:

我想你可能需要遵循调用readfile()通过调用exit() ,以确保没有其他被写入到输出缓冲器。



Answer 5:

另外,尝试file_get_contents() ,而不是readfile() 我觉得它的工作原理下更多的情况。 我也建议你使用ob_flush()你输出后的图像数据。 我从来没有需要使用ob_clean()flush()来获得这样的工作的事情。

正如埃里克说,你可能还需要把调用exit()在那里,以及良好的措施,如果仍无法以防万一的工作,你越来越停留在年底一些垃圾数据。



文章来源: Creating a download link for .jpg file using PHP