首页 > 解决方案 > 为什么从php下载文件只有1kb?

问题描述

我尝试从服务器中的 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);
?>

标签: phpfiledownload

解决方案


首先,你应该修复你的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;
}

推荐阅读