Search code examples
phpzipphp-ziparchive

Zip files generated by PHP file


I am needing to parse a series of php files to output .PDFs and .PNGs files before zipping them using zipArchive. What I would like to do is something like

$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);

//If you access qr_gen.php on a browser it creates a QR PNG file.
$zip->addFile('qr_gen.php?criteria=1', 'alpha.png');
$zip->addFile('qr_gen.php?criteria=2', 'beta.png');
//If you access pdf_gen.php on a browser it creates a PDF file.
$zip->addFile('pdf_gen.php?criteria=A', 'instructions.pdf');

$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file);

This obviously does not work. How can I accomplish my goal?


Solution

  • The following line will not work as you provide and url as filename:

    $zip->addFile('qr_gen.php?criteria=1', 'alpha.png');
    

    Instead you'll have to download the pngs first and store them locally. Then add them to the zip archive. Like this:

    file_put_contents('alpha.png', 
        file_get_contents('http://yourserver.com/qr_gen.php?criteria=1');
    
    $zip->addFile('alpha.png');
    

    You'll find more information at the documentation page of ZipArchive::addFile()