PHP Force下载导致0字节文件

Ale*_*lex 7 php download

我正在尝试使用PHP从我的Web服务器强制下载文件.我不是PHP的专家,但我似乎无法解决大小为0字节的文件下载问题.

码:

$filename = "FILENAME...";

header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
set_time_limit(0);
readfile($file);
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?谢谢.

Rob*_*itt 7

您没有检查该文件是否存在.试试这个:

$file = 'monkey.gif';

if (file_exists($file))
{
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    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));
    ob_clean();
    flush();
    readfile($file);
    exit;
}else
{
    echo "File does not exists";
}
Run Code Online (Sandbox Code Playgroud)

看看你得到了什么.


您还应该注意,这会强制下载为八位字节流,即纯二进制文件.有些浏览器很难理解文件的确切类型.例如,如果您发送标题为GIF的GIF Content-Type: application/octet-stream,则浏览器可能不会将其视为GIF图像.您应该添加特定检查以确定文件的内容类型,并发送适当的Content-Type标头.


Ali*_*xel 4

我在phunction中使用以下方法,到目前为止还没有遇到任何问题:

function Download($path, $speed = null)
{
    if (is_file($path) === true)
    {
        $file = @fopen($path, 'rb');
        $speed = (isset($speed) === true) ? round($speed * 1024) : 524288;

        if (is_resource($file) === true)
        {
            set_time_limit(0);
            ignore_user_abort(false);

            while (ob_get_level() > 0)
            {
                ob_end_clean();
            }

            header('Expires: 0');
            header('Pragma: public');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Content-Type: application/octet-stream');
            header('Content-Length: ' . sprintf('%u', filesize($path)));
            header('Content-Disposition: attachment; filename="' . basename($path) . '"');
            header('Content-Transfer-Encoding: binary');

            while (feof($file) !== true)
            {
                echo fread($file, $speed);

                while (ob_get_level() > 0)
                {
                    ob_end_flush();
                }

                flush();
                sleep(1);
            }

            fclose($file);
        }

        exit();
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

您可以简单地尝试一下:

Download('/path/to/file.ext');
Run Code Online (Sandbox Code Playgroud)