Php download script outputs corrupted file

前端 未结 2 1754
南笙
南笙 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: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..

提交回复
热议问题