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