Php 将文件从服务器下载到客户端';s计算机

Php 将文件从服务器下载到客户端';s计算机,php,performance,security,download,Php,Performance,Security,Download,我的根目录中有一个名为files的文件夹。 此文件夹包含的文件范围为1KB-1GB 我想要一个php脚本,它可以简单地使用AJAX异步下载文件 此代码在单击文件时启动下载脚本: JQUERY $('.download').click(function(){ var src =$(this).attr('src'); $.post('download.php',{ src : src //contains name of file },function(da

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


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

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

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!
?>


下载文件的最佳、最快和安全的方法是什么

为了继续原始答案,我添加了一些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);

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

如果我不知道
内容类型怎么办
?请不要在需要时使用它。它可以帮助浏览器确定文件打开的程序(电影、图像、MS word等)。您不能使用内容类型。PHP将默认声明它是HTML文档,除非您覆盖该.Upvote。。。。我不想吹毛求疵,但你对“文件出口”有一个拼写错误。它应该是“文件\存在”。有些人可能不知道如何更正这个错误,所以请更正它。“我想要一个php脚本,可以使用AJAX异步下载文件。”-为什么?你需要做什么,而仅仅让服务器来管理是做不到的?为什么需要使用Ajax?
$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);