簡體   English   中英

PHP 無法打開下載的 zip 但服務器上的文件可以打開

[英]PHP can't open downloaded zip but the file on the server is openable

我使用 ZipArchive 創建 zip 文件。 除了一件事 - 將其作為附件下載之外,一切都很好。 當我嘗試打開下載的文件 7-zip 時說:“無法打開文件......作為存檔”。 保存在服務器上的文件一切正常。 當我嘗試將下載的文件與存儲在服務器上的文件進行比較時,文件末尾的差異很小。

簡單地說:服務器上的存檔打開但下載后它沒有

我使用的代碼:

$file='Playlist.zip';
    if (headers_sent()) {
        echo 'HTTP header already sent';
    } else {
        if (!is_file($file)) {
            header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
            echo 'File not found';
        } else if (!is_readable($file)) {
            header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
            echo 'File not readable';
        } else {
            header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
            header("Content-Type: application/zip");
            header("Content-Length: ".filesize($file));
            header("Content-Disposition: attachment; filename=".basename($file)."");
            header("Pragma: no-cache"); 
            header("Expires: 0");
            set_time_limit(0);
            $handle = fopen($file, "rb");
            while (!feof($handle)){
                echo fread($handle, 8192);
            }
            fclose($handle);
        }
    }

區別

嘗試使用fpassthru()

$file="Playlist.zip";
if (headers_sent()) {
    echo "HTTP header already sent";
} else {
    if (!is_file($file)) {
        header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
        echo "File not found";
    } else if (!is_readable($file)) {
        header($_SERVER['SERVER_PROTOCOL'] . " 403 Forbidden");
        echo "File not readable";
    } else {
        header($_SERVER['SERVER_PROTOCOL'] . " 200 OK");
        header("Content-Type: application/zip");
        header("Content-Length: " . filesize($file));
        header("Content-Disposition: attachment; filename=" . basename($file));
        header("Pragma: no-cache"); 
        $handle = fopen($file, "rb");
        fpassthru($handle);
        fclose($handle);
    }
}

執行 $data=ltrim($data) 以刪除下載的 ZIP 文件中的前導空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM