send zip file to browser / force direct download

后端 未结 4 1318
感情败类
感情败类 2020-12-06 00:47

i created with php zip ( http://php.net/manual/de/book.zip.php ) a zip file

now i have to send it to the browser / force a download for it.

相关标签:
4条回答
  • 2020-12-06 01:05
    <?php
        // or however you get the path
        $yourfile = "/path/to/some_file.zip";
    
        $file_name = basename($yourfile);
    
        header("Content-Type: application/zip");
        header("Content-Disposition: attachment; filename=$file_name");
        header("Content-Length: " . filesize($yourfile));
    
        readfile($yourfile);
        exit;
    ?>
    
    0 讨论(0)
  • 2020-12-06 01:11

    If you already have your ZIP on the server, and if this ZIP is reachable by Apache in HTTP or HTTPS, then, you should redirect to this file instead of "reading it" with PHP.

    It's much more efficient as you don't use PHP, so no CPU or RAM are needed, and it will be faster to download, as no reading/writing by PHP needed too, only direct download. Let's Apache do the job!

    So a nice function could be:

    if($is_reachable){
        $file = $relative_path . $filename; // Or $full_http_link
        header('Location: '.$file, true, 302);
    }
    if(!$is_reachable){
        $file = $relative_path . $filename; // Or $absolute_path.$filename
        $size = filesize($filename); // The way to avoid corrupted ZIP
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Length: ' . $size);
        // Clean before! In order to avoid 500 error
        ob_end_clean();
        flush();
        readfile($file);
    }
    exit(); // Or not, depending on what you need
    

    I hope that it will help.

    0 讨论(0)
  • 2020-12-06 01:14

    You need to do it this way, otherwise your zip will be corrupted:

    $size = filesize($yourfile);
    header("Content-Length: \".$size.\"");
    

    So content-length header needs a real string, and filesize returns and integer.

    0 讨论(0)
  • 2020-12-06 01:28

    Set the content-type, content-length and content-disposition headers, then output the file.

    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Content-Length: '.filesize($filepath) );
    readfile($filepath);
    

    Setting Content-Disposition: attachment will suggest the browser to download the file instead of displaying it directly.

    0 讨论(0)
提交回复
热议问题