【问题标题】:Downloading a file from server to client's computer将文件从服务器下载到客户端计算机
【发布时间】:2014-10-04 11:32:42
【问题描述】:

我的根目录中有一个名为files 的文件夹。 此文件夹包含范围从1 Kb-1 GB 的文件。

我想要一个可以简单地使用 AJAX 异步下载文件的 php 脚本。

此代码在单击文件时启动下载脚本:

JQUERY

$('.download').click(function(){
   var src =$(this).attr('src');  
   $.post('download.php',{
      src :  src //contains name of file 
    },function(data){
      alert('Downloaded!');
    });
});

PHP

<?php
   $path = 'files/'.$_POST['src'];
   //here the download script must go!
?>

哪种方式是下载文件的最佳、最快和安全

【问题讨论】:

  • "我想要一个可以简单地使用 AJAX 异步下载文件的 php 脚本。" - 为什么?您需要做哪些仅让服务器管理无法完成的事情?为什么需要涉及 Ajax?

标签: php performance security download


【解决方案1】:
<?php
/**
 * download.php
 */

if (!empty($_GET['file'])) {
    // Security, down allow to pass ANY PATH in your server
    $fileName = basename($_GET['file']);
} else {
    return;
}

$filePath = '???/files/' . $fileName;
if (!file_exists($filePath)) {
    return;
}

header("Content-disposition: attachment; filename=" . $fileName);
header("Content-type: application/pdf");
readfile($filePath);

实际上AJAX请求是不必要的,当使用Content-disposition: attachment时:

<a href="download.php?file=file1.pdf">File1</a>

【讨论】:

  • 如果我不知道content-type 怎么办?
  • 只是不要在什么时候使用它。它帮助浏览器确定打开文件的程序(电影、图像、MS word 等)
  • 您不能不使用 Content-Type。 PHP 将默认声明它是一个 HTML 文档,除非你覆盖它。
  • 赞成.... 不想成为挑剔者,但您的“file_exits”有错字。它应该是'file_exists'。有些人可能不知道如何纠正这个错误,所以请纠正它。
【解决方案2】:

为了继续原来的答案,我添加了一些 php 函数以使其更具程序性:

$filePath = $_GET['path'];
$fileName = basename($filePath);
if (empty($filePath)) {
    echo "'path' cannot be empty";
    exit;
}

if (!file_exists($filePath)) {
    echo "'$filePath' does not exist";
    exit;
}

header("Content-disposition: attachment; filename=" . $fileName);
header("Content-type: " . mime_content_type($filePath));
readfile($filePath);

如果您的服务器需要强大的安全性,请不要在未在同一脚本中预先验证用户的情况下使用此功能。或使用原始答案发布的安全措施。此脚本将允许用户下载您服务器上的任何文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    相关资源
    最近更新 更多