belinea
belinea

Reputation: 123

Downloading zip and exe in php. Followed guidelines, getting weird result

I know there's been plenty of threads on this, but I'm facing pecular problem here

First of all, I'm trying to output a zip file for download. I have the following code

        $file = '/home/www/public/'.$filename;
        header('Content-Type: application/zip');
        header("Content-Transfer-Encoding: Binary");
        header('Content-disposition: attachment; filename='.$filename.'');
        header('Content-Length: '.filesize($file));

        echo readfile($file);

The problem is, zip downloaded with these headers is corrupted. Can't open it (unexpected end of archive). It is not corrupted when I remove Content-length header - but then, user cannot see the downloading time.

I also wanted to adapt same code for exe files (just changing type to application/octet-stream) but I got same result. Files themselves are fine for sure. It's just during the download something screws up

Any help appreciated

Below is the ACTUAL code I'm using (after two changes suggested already). I simplified it for stackoverflow but perhaps there's something in there

        $id = post('file');
        $object = Software_Files_Model::create()->find($id);

        if ($object->software) {    
           $file = '/home/www/public'.$object->software->getPath();
           $size=$object->software->size;

           header('Content-Type: application/zip');
           header("Content-Transfer-Encoding: Binary");
           header('Content-Disposition: attachment; filename='.$object->software->name.'');
           header('Content-Length: '.$size);

           readfile($file);
           exit;
        }

Just to add again, file downloads as a whole. If it weights 10 megs, all 10 megs downloads fine, keeping the filename and all. I can even open the zip archive and see the content. It's during uzipping when the message comes up

Upvotes: 0

Views: 840

Answers (1)

Dragony
Dragony

Reputation: 1722

You're only using $filename on filesize() instead of the complete path as defined in $file on line 1.

Upvotes: 1

Related Questions