【问题标题】:Why download file from php only 1kb?为什么从php下载文件只有1kb?
【发布时间】:2018-12-21 02:27:31
【问题描述】:

我尝试从服务器中的 php 强制下载 pdf 文件...但我下载的所有文件只有 1kb 大小。它与实际大小不同,我需要在下载前声明文件大小吗?

<?php
$path = "C:\Users\omamu02\Desktop\TESTPRINT" ;
$file = "NMT PRV PHG 370 2017.pdf";
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-disposition: attachment; filename= $file"); //Tell the filename to the browser
header("Content-type: application/force-download");//Get and show report format 
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
readfile($path); //Read and stream the file
get_curret_user();
error_reporting(0);
?>

【问题讨论】:

    标签: php file download


    【解决方案1】:

    首先,您应该修复 filename= $file 标头。至少用 ' 字符包装您的 $file 变量。此外,您不需要在 PHP 文件末尾添加结束标记。

    我不确定你的标题,所以我建议你试试下面的函数,它对于任何类型的数据都很常见,并且已经包含一些错误修复和解决方法:

    function download_file($file_path, $file_name = null, $file_type = 'application/octet-stream')
    {
        if ($file_name === null)
        {
            $file_name = basename($file_path);
        }
    
        if (file_exists($file_path))
        {
            @set_time_limit(0);
    
            header('Content-Description: File Transfer');
            header('Content-Type: ' . $file_type);
            header('Content-Disposition: attachment; filename="' . str_replace('"', "'", $file_name) . '"');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_path));
    
            readfile($file_path);
        }
    
        exit;
    }
    

    【讨论】:

    • 同样的结果打不开文件大小1 kb实际233kb
    • 哦,听起来你的路径是错误的。试试readfile($path . '\' . $file);,你应该在readfile函数中提供文件的完整路径,而不仅仅是一个目录。
    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 2021-04-10
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 2011-10-07
    • 2015-11-15
    相关资源
    最近更新 更多