3

I'd like a bit of help debugging this code. I'm trying to zip some files, which I provide as paths to Ziparchive. I think the zip file is empty, possibly. When I test this on a staging site I get a 'decompression failed' error. When I test this locally I get the following error in php logs

PHP Warning: readfile(images.zip): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/8018_Whites/wordpress/downloadzip.php on line 29.

Here is the code:

<?php

//get image urls string
//$cat_string = "url1,url2,url3..."
if (isset($_GET['category-images'])) {
    $cat_string=$_GET['category-images'];
}
//change string to array
$cat_array=explode(",", $cat_string);
$files=$cat_array;

$zipname = 'images.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  if(!strstr($file,'.php')) $zip->addFile($file);
}
$zip->close();

if ($zipname) {
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
exit();
}
?>

Do I need to add ob_start/ob_flush to this code, and should I put the ob_flush after readfile?

2 Answers2

0

All files and Zip folder to give absolute path. so zip is properly created.

<?php
$zip_root ='/var/www/gplhome/'
$file_root ='/var/www/gplhome/project/'

    //get image urls string
    //$cat_string = "url1,url2,url3..."
    if (isset($_GET['category-images'])) {
        $cat_string=$_GET['category-images'];
    }
    //change string to array
    $cat_array=explode(",", $cat_string);
    $files=$cat_array;

    $zipname = $zip_root.'images.zip';
    $zip = new ZipArchive;


    if ($zip->open($zipname, ZIPARCHIVE::CREATE) != TRUE) {
        die("Could not open archive");
    }

    foreach ($files as $file) {
      if(!strstr($file_root.$file,'.php')) $zip->addFile($file_root.$file);
    }
    $zip->close();

if ($zipname) {
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));
    readfile($zipname);
    exit();
}
?>
eisbehr
  • 12,243
  • 7
  • 38
  • 63
Gopal Rathod
  • 150
  • 7
0
  • check the return value of $zip->close(), it returns false on error.
  • check the return value of $zip->addFile(), it returns false on error.
  • ensure that you use only file name for headers and full name for readfile.
  • check if the file is created. Replace

if ($zipname) {

with

if (is_readable($zipname)) {

  • don't put ?> and the end of the php file
Alex
  • 4,621
  • 1
  • 20
  • 30