Search code examples
phpgetzipphp-ziparchive

how to add files to zip using php, and these files should have a GET parameters


I have a file gen.php this file should have some GET parameters like: gen.php?oid=35852 when open this link: gen.php?oid=35852 will generate for download file called 35852.txt using some php headers

now I'm trying to add these generated files to a zip archive using php ZipArchive() but it is not working

$zip = new ZipArchive(); // Load zip library 
$zip_name = time().".zip"; // Zip name

if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ 
   // Opening zip file to load files
   $error .= "* Sorry ZIP creation failed at this time";
}

//this file will not added
$zip->addFile('/../../ser/gen.php?oid=35851');
//this file will not added
$zip->addFile('../ser/gen.php?oid=35852');
//this file will added, but as you see it will be the PHP file
$zip->addFile('../ser/gen.php');
//this file will added as a sample file
$zip->addFile('../samples2/2.png');

$zip->close();

is there any way to add the result files of gen.php?oid=35851 that should be: 35851.txt to the zip archive?


Solution

  • If you want to download contents generated by gen.php?oid=35852 into 35852.txt file, and then compress the downloaded file in Zip, then you can use a code similar to the following.

    $id = 35851;
    $url = "http://yourdomain.com/gen.php?oid=$id";
    
    $txt_name = "${id}.txt";
    $zip_name = "${id}.zip";
    
    $zip = new ZipArchive();
    
    if ($zip->open($zip_name, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
       die("Failed to create zip archive $zip_name");
    }
    
    if (! $text = file_get_contents($url)) {
      die("Failed to download $url");
    }
    
    if (false === file_put_contents($txt_name, $text)) {
      die("Failed to write to $txt_name");
    }
    
    if (! $zip->addFile($txt_name)) {
      unlink($txt_name);
      die("Failed to add $txt_name to $zip_name");
    }
    
    $zip->close();
    
    unlink($txt_name);