PHP>下载ZIP:网络错误

时间:2018-07-17 20:56:41

标签: php

我的php代码有一个大问题,我使用html表单获取“文件名”,可以正常工作,但是我的问题是:启动下载时,所有浏览器的下载zip文件都出现了,并且出现网络错误,例如:578ko / 600ko:网络错误。

<?php
$dir = "lol/"; // trailing slash is important
$file = $dir .$_POST['filename'] ;

if (file_exists($file)) {
    header('Pragma: public');
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Transfer-Encoding: binary");
    header("Content-type: application/zip");
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Cache-Control: must-revalidate');
    header('Content-Length: ' . filesize($file));

    readfile($file);

} else {
    echo "Le fichier $file n'existe pas.";
}
exit;
?>

2 个答案:

答案 0 :(得分:1)

检查您的Web服务器超时值,并将其增加/定义为更高的值。同时关闭输出缓冲。

<?php
$dir = "lol/"; // trailing slash is important
$file = $dir .$_POST['filename'] ;
//Turn off output buffering
if (ob_get_level())
   ob_end_clean();

if (file_exists($file)) {
    header('Pragma: public');
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Transfer-Encoding: binary");
    header("Content-type: application/zip");
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Cache-Control: must-revalidate');
    header('Content-Length: ' . filesize($file));

    readfile($file);

} else {
    echo "Le fichier $file n'existe pas.";
}
exit;
?>

答案 1 :(得分:0)

您可以尝试读取和发送数据块-可能会有帮助

<?php

    $dir = "lol/"; // trailing slash is important
    $file = $dir . $_POST['filename'] ;

    if( file_exists( $file ) ) {

        header('Pragma: public');
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Transfer-Encoding: binary");
        header("Content-type: application/zip");
        header('Content-Disposition: attachment; filename=' . basename( $file ) );
        header('Cache-Control: must-revalidate');
        header('Content-Length: ' . filesize( $file ) );

        /*
            send the file in chunks rather than trying to read and send all at once
        */
        if( $fh = @fopen( $file, 'rb' ) ) {
            while( !@feof( $fh ) and ( connection_status()==0 ) ) {
                print( fread( $fh, 1024*8 ) );
                flush();
            }
            @fclose( $fh );
        }

    } else {
        echo "Le fichier $file n'existe pas.";
    }
    exit;
?>