从服务器php下载文件 [英] Download files from server php

查看:96
本文介绍了从服务器php下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个URL,用于保存工作中的某些项目,它们大部分是MDB文件,但也有一些JPG和PDF.

I have a URL where I save some projects from my work, they are mostly MDB files, but some JPG and PDF are there too.

我需要做的是列出该目录中的每个文件(已经完成),并为用户提供下载文件的选项.

What I need to do is to list every file from that directory (already done) and give the user the option to download it.

使用PHP如何实现?

推荐答案

要读取目录内容,可以使用

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

download.php中,您可以强制浏览器发送下载数据,并使用 basename()进行确保客户端不会传递其他文件名,例如../config.php

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}

这篇关于从服务器php下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆