0

I noticed something slightly odd today, whilst making a script to download a zip file.

Here's the script, which gets files in a directory, and presents it to the client to download:

<?php
$directory='/dir';
$d = scandir($directory);
$zip = new ZipArchive();
$zipname = 'dir' . time() . 'zip';
if($zip->open($zipname, ZIPARCHIVE::CREATE)===true){
    foreach($d as $f){
        if($f!='.'&&$f!='..'){
            $zip->addFile($directory.'/'.$f, $f);
        }
    }
} else {
    echo 'Error';
}
$zip->close();
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zipname.'"');
readfile($zipname);
unlink($zipname);
?>

As it is, it works. But, if I put a new empty line at the top (before <?php), it still works, but the file that is downloaded is corrupt. Strange huh.

I was kinda thinking that this may be a 'headers already sent' error, but there's no errors in the log ...

Could anyone shed some light as to why this happens? Is it a server-side fault, or client side? Thanks in advanced.

This script was an edit of: http://wcetdesigns.com/tutorials/2012/11/01/zip-archive.html

Just Lucky Really
  • 1,341
  • 1
  • 15
  • 38
  • 2
    With a newline character before your opening ` – esqew May 21 '14 at 14:44
  • Putting the space at the top triggers headers, and also that space becomes part of the downloaded file. Zip files have a specific "magic number" signature at the start of the file, and by adding that space, you're throwing off the magic number signature, making it a "not a zip" file. – Marc B May 21 '14 at 14:51
  • Yep, that's what I was thinking. But I just find it odd how I don't get any server-side errors, and that the file is corrpt ... Specifically the error is: `Windows cannot open the folder. The compressed (Zipped) folder C:\foo is invalid` @esqew – Just Lucky Really May 21 '14 at 14:51
  • Ahh ... I see ... That kinda makes sense I guess Lol @MarcB ... Thanks for the info, and here's a picture of a bunny rabbit driving: http://img1.wikia.nocookie.net/__cb20090323192024/uncyclopedia/images/9/97/Bunny_car.jpg – Just Lucky Really May 21 '14 at 14:56

0 Answers0