Readfile返回一个空文件

时间:2019-07-10 08:15:05

标签: php file download readfile

我有这段代码可以强制下载,$file是现有.jpg,.png或.pdf文件(我确定存在)的 url

 <?php
    $file = $_REQUEST['file'];
    $file_extension = end(explode('.', $file));
    $file_name = end(explode('/', $file));
    switch ($file_extension) {
        case 'jpg':
            header('Content-Type: image/jpeg');
            header('Content-Disposition: attachment; filename='.$file_name);
            header('Pragma: no-cache');
            readfile($file);
            break;
        case 'png':
            header('Content-Type: image/png');
            header('Content-Disposition: attachment; filename='.$file_name);
            header('Pragma: no-cache');
            readfile($file);
            break;
        case 'pdf':
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename='.$file_name);
            header('Pragma: no-cache');
            readfile($file);
            break;
    }

但是它正在下载一个空的(0KB)文件(具有正确的名称)

有没有想到会发生什么事?

2 个答案:

答案 0 :(得分:1)

由于file_get_contents()也返回null,因此您的问题可能是php.ini配置中的设置。

参数 allow_url_fopen 必须为打开

答案 1 :(得分:0)

那是因为您缺少Content-Length标头。

尝试一下:

$file = $_REQUEST['file'];
$file_extension = end(explode('.', $file));
$file_name = end(explode('/', $file));

switch ($file_extension) {
    case 'jpg':
        header('Content-Type: image/jpeg');
        break;
    case 'png':
        header('Content-Type: image/png');
        header('Content-Disposition: attachment; filename='.$file_name);
        break;
    case 'pdf':
        header('Content-Type: application/pdf');
        break;
}

header('Content-Disposition: attachment; filename='.$file_name);
header('Pragma: no-cache');
header('Content-Length: ' . filesize($file));

// You may want to add this headers too (If you don't want the download to be resumable - I think).
header('Expires: 0');
header('Cache-Control: must-revalidate');

// And you may consider flushing the system's output buffer if implicit_flush is turned on in php.ini.
flush();

// If you have the file locally.
readfile($file);

// Otherwise,
echo file_get_contents($file); // You should have allow_url_include on in php.ini

无法尝试,但应该可以。