Download of .zip file runs a corrupted file php

后端 未结 7 426
误落风尘
误落风尘 2020-12-03 17:04

I\'m trying to force a download of a protected zip file (I don\'t want people to access it without logging in first.

I have the function created for the login

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 18:05

    This issue can have several causes. Maybe your file is not found or it can not be read and thus the file’s content is just the PHP error message. Or the HTTP header is already sent. Or you have some additional output that then corrupts your file’s content.

    Try to add some error handling into your script like this:

    $file='../downloads/'.$filename;
    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-Transfer-Encoding: Binary");
            header("Content-Length: ".filesize($file));
            header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
            readfile($file);
            exit;
        }
    }
    

提交回复
热议问题