Php download script outputs corrupted file

前端 未结 2 1706
南笙
南笙 2021-01-27 12:21

I was building a file download Class for my CMS in PHP, at a time I noticed it outputs files in a different Encoding format. I tried with readfile, file_get_contents,fread but a

相关标签:
2条回答
  • 2021-01-27 12:40

    The problem lies in the Content-Disposition header. This header is not really part of the HTTP protocol, see RFC 2616, 15.5 Content-Disposition Issues

    Content-Disposition is not part of the HTTP standard, but since it is widely implemented, we are documenting its use and risks for implementors.

    And later in section 19.5.1 Content-Disposition

    The Content-Disposition response-header field has been proposed as a means for the origin server to suggest a default filename if the user requests that the content is saved to a file.
    ...
    An example is

    Content-Disposition: attachment; filename="fname.ext"
    

    If this header is used in a response with the application/octet- stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.

    Leaving out this header shows the contents of the sent file.

    I have tested this with Firefox only, so other web browsers might behave different.

    0 讨论(0)
  • 2021-01-27 12:49

    Try running an ob_start() as the first thing in your script, write stuff, edit your headers and then ob_flush() and ob_clean() whenever you want your content to be sent to the user's browser.

    This is worked for me..

    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;
    }
    

    Hope this helps..

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