如何在 PHP 中强制下载文件

2022-01-02 00:00:00 download php html

我有图片列表,我想要一个下载"链接以及每张图片,以便用户可以下载图片.

I have list of images and I want a "Download" link along with every image so that user can download the image.

那么有人可以指导我如何为 php 中的任何文件提供下载链接吗?

so can someone guide me How to Provide Download link for any file in php?

编辑

我希望在单击下载链接时显示下载面板我不想导航到要在浏览器上显示的图像

I want a download panel to be displayed on clicking the download link I dont want to navigate to image to be displayed on the browser

推荐答案

如果你想强制下载,你可以使用类似下面的方法:

If you want to force a download, you can use something like the following:

<?php
    // Fetch the file info.
    $filePath = '/path/to/file/on/disk.jpg';

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?>

如果您只是使用普通链接链接到此脚本,则会下载该文件.

If you simply link to this script using a normal link the file will be downloaded.

顺便说一句,上面的代码片段需要在页面开始时执行(在任何标题或 HTML 输出发生之前.)如果您决定基于此创建一个用于下载任意文件的函数,也要小心- 您需要确保防止目录遍历(realpath 是方便),如果您接受来自 $_GET 或 $_POST 的输入,则仅允许从定义的区域内下载.

Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.

相关文章