Search code examples
phphttp-headersphp-ziparchive

PHP Closing zipArchive prints junk text (data dump)


I've been trying to learn how to properly use the zipArchive function in php to create and download a zip folder containing selected files.

It works, after a fashion, creating the zip file and storing it on the server, but I haven't been able to get the download to start automatically and after the $zip->close(); command it prints pages and pages of junk characters as if it were printing the zip file. Here's what part of that looks like: http://www.abpdigital.com/uploads/Junk%20Text.png

I got my basic code from here: http://roshanbh.com.np/2008/09/force-download-mutiple-files-zip-archive-php.html

and here's how it looks in my code:

function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
    {
        //create the object
        $zip = new ZipArchive();
        //create the file and throw the error if unsuccessful
        if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==TRUE)
        {
            exit("cannot open <$archive_file_name>\n");
        }

        //add each files of $file_name array to archive
        foreach($file_names as $files)
        {
            $zip->addFile($file_path.$files,$files);
        }
        $zip->close();

        //THIS IS WHEN THE JUNK TEXT STARTS

        //then send the headers to force download the zip file
        header("Content-type: application/zip");
        header("Content-Disposition: attachment; filename=".$archive_file_name);
        header("Pragma: no-cache");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
        readfile($archive_file_name);
        exit;
    }

Does anyone have an idea of what might be causing the junk text? Am I using the headers incorrectly? I can provide further code if necessary, but I'm fairly certain the variable passes are solid. I've been testing in Chrome, but I've verified that this behavior persists in both IE and Firefox.

[UPDATE] I found that if I create the zip file in a subfolder of the current directory (instead of directly in the current directory), it doesn't output all the junk text on the page.

Now my issue is more that the auto-download functionality I was hoping to get from the headers isn't and has never worked. Anything I should be looking for as far as errors or events that might shed some light on what's wrong?


Solution

  • It seems to be that there is something wrong with the headers. The wired junk displayed is just the raw-data from the zip-file. Please check $archive_file_name if its right. Try to change the headers as following:

    // It should contain only the filename not the complete path
    header("Content-Disposition: attachment; filename=".basename($archive_file_name));
    
    // Adding file-size to header
    header("Content-Length: " . filesize($archive_file_name));
    
    // Check that is path to zip with filename
    readfile($archive_file_name);