View Full Version : readfile in php isn't downloading zip file

07-10-2012, 11:44 PM
I've got the following code to force a file download for a zipfile that I just created:

$zip_name = 'download.zip';
$result = create_zip($other_files_to_zip,$zip_name,true);
echo "The filesize is: ".filesize($zip_name);
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=filename.zip');
header('Content-Length: ' . filesize($zip_name));

When I echo out the filesize it shows a correct size and it prompts me to download the filename.zip which is ok since it's just a filename but then when I save the document and try and open Windows says that Windows cannot open the folder because the folder is invalid.

Any ideas on how to resolve an issue like this?

Thanks in advance!

07-10-2012, 11:50 PM
Having had to figure this out myself, I tell you that when you make a download.php it has to be in a separate file, with no spaces before or after the php tags and called by a simple href link to it. You can pretty much put what you want in it, run whatever code, but it has to be made that way.

07-11-2012, 12:07 AM
Are you sure? It seems like you have to be able to force a download because I've done it for some excel exports that I run. I'm just not sure why it's not working for my zip file. This is the first time using readfile though...

07-11-2012, 02:04 AM
Are you sure?


Your download.php file must contain no spaces before the <?php tag and no spaces after the ?> tag otherwise it will corrupt the filestream output. Again, you have to call the download.php file via a link and not as part of a webpage. A webpage script puts out html - so you can't output a filestream in the middle of that can you - the browser won't have any idea what to do with it.

Additionally, you need to test one small file being downloaded - say 100Kb in size. Download it and open it in notepad++ or similar and look in there for any php error messages.

Also check the MD5 hashes before and after download. In php use md5_file() to generate the hash and log it to a DB table so that you can get to it without affecting the filestream. Once downloaded, compare that hash with one you generate locally on the file on your system. If they differ then you have a problem somewhere.

I've done a lot of file download coding in the past :thumbsup:

07-12-2012, 12:33 AM
Have you had any luck getting this working?

07-12-2012, 12:38 AM
Yeah but not how I wanted it to. Like you suggested I return a link using jQuery and then allow the user to click on a link to download the file. I pass the filename to my download.php file and then it works fine.

07-12-2012, 12:53 AM
Glad you've got it working :thumbsup: