Search code examples
phplinuxfileheadertransfer

php header file transfer corrupted


I have some files in a folder. i use the following php code to transfer the file to browser (with headers).

i download the correct length of file in .7z format but i can't unzip it. if i transfer the same file with ftp, i can unzip it without problem. From my server i can unzip it without problem to. so the error is somewhere in php

    private function pushToBrowser($file){
    if(!$file){ // file does not exist
        die('file not found');
    } else {
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        header("Content-length: ".filesize($file).";\n");

        // read the file from disk
        readfile($file);
    }
}

an the usage ot the code

$this->pushToBrowser($path);

Solution

  • before you call readfile($path) do a ob_clean(); & flush();

    so finally your code should look like:

    private function pushToBrowser($file){
        if(!$file){ // file does not exist
            die('file not found');
        } else {
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header("Content-Disposition: attachment; filename=$file");
            header("Content-Type: application/x-7z-compressed");
            header("Content-Transfer-Encoding: binary");
            header("Content-length: ".filesize($file).";\n");
            ob_clean();
            flush();
            // read the file from disk
            readfile($file);
        }
    }