【问题标题】:PHP force download, download without naming the file the full path namePHP强制下载,下载不命名文件全路径名
【发布时间】:2014-05-01 23:26:26
【问题描述】:

因此,我们的系统通过将用户图像存储在用户文件夹中来工作,用户文件夹存储在主用户文件夹中,主用户文件夹存储在一个名为 client_folders 的文件夹中。

每次我尝试构建我们的下载脚本(使用 php 强制下载)时,下载的文件都带有整个文件路径的名称

示例:client_folder/user_30/client_130/image.jpg

我只是想让文件说 image.jpg

我已经尝试了几件事,使用数组 pop、basename() 爆炸,但每次我尝试这些选项之一时,readfile() 函数读取的变量都是空的。

现在在 mysql 中,我将整个文件路径(包括文件名)存储在一列中,这是正确的方法吗?以及如何下载没有完整路径的文件

如果有帮助,这是成功下载的代码....只需完整路径名:(

ob_clean();
if(isset($_POST['file_name'])){
$file = $_POST['file_name'];
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile($file);
exit();
}

【问题讨论】:

    标签: php download


    【解决方案1】:

    在 readfile 中,您必须传递完整路径,但在文件名中为用户提供文件名的标题:

    ob_clean();
    if(isset($_POST['file_name'])){
    $file_for_user = $_POST['file_name'];
    $full_path_file = "STORAGE_PATH".$file_for_user;
    header("Content-type: application/octet-stream");
    header('Content-Disposition: attachment; filename="'.$file_for_user.'"');
    readfile($full_path_file);
    exit();
    }
    

    【讨论】:

    • 我会删除标题("Content-type: application/octet-stream");因为在这种情况下它实际上无济于事。 media-division.com/…
    【解决方案2】:

    如果您使用 mysql 中的引用文件路径动态拉取文件以供下载,并且您希望下载具有文件名而不是此处的路径,这就是您所做的

    ob_clean();
    if(isset($_POST['file_name'])){
    $file = $_POST['file_name'];
    $filename = basename($file);
    header("Content-type: application/octet-stream");
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    readfile($file);
    exit();
    }
    

    这里是注释版

    //This cleans the cache (just a precaution)
    ob_clean();
    
    //Grab the file path from the POST global
    if(isset($_POST['file_name'])){
    
    //Put the global variable into a regular variable
    $file = $_POST['file_name'];
    
    //Use basename() to separate the name of the file from the reference path and put it in a variable
    $filename = basename($file);
    
    //I have no idea if this is needed  but everyone uses it 
    header("Content-type: application/octet-stream");
    
    //Use this header to name your file that is being downloaded, use the variable that is storing the file name you grabbed using basename()
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    
    //useread file function to send info to buffer and start download, use the variable that contains the full path
    readfile($file);
    exit();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多