Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ZipArchive is not adding any files (Windows)

I'm failing to put even a single file into a new zip archive.

makeZipTest.php:

<?php

$destination = __DIR__.'/makeZipTest.zip';
$fileToZip = __DIR__.'/hello.txt';

$zip = new ZipArchive();
if (true !== $zip->open($destination, ZIPARCHIVE::OVERWRITE)) {
    die("Problem opening zip $destination");
}
if (!$zip->addFile($fileToZip)) {
    die("Could not add file $fileToZip");
}
echo "numfiles: " . $zip->numFiles . "\n";
echo "status: " . $zip->status . "\n";
$zip->close();

The zip gets created, but is empty. Yet no errors are triggered.

What is going wrong?

like image 880
CL22 Avatar asked Aug 12 '15 05:08

CL22


Video Answer


2 Answers

It seems on some configuration, PHP fails to get the localname properly when adding files to a zip archive and this information must be supplied manually. It is therefore possible that using the second parameter of addFile() might solve this issue.

ZipArchive::addFile

Parameters

  • filename
    The path to the file to add.
  • localname
    If supplied, this is the local name inside the ZIP archive that will override the filename.

PHP documentation: ZipArchive::addFile

$zip->addFile(
    $fileToZip, 
    basename($fileToZip)
);

You may have to adapt the code to get the right tree structure since basename() will remove everything from the path apart from the filename.

like image 152
spenibus Avatar answered Oct 09 '22 01:10

spenibus


You need to give server right permission in folder where they create zip archive. You can create tmp folder with write permision chmod 777 -R tmp/

Also need to change destination where script try to find hello.txt file $zip->addFile($fileToZip, basename($fileToZip))

<?php

$destination = __DIR__.'/tmp/makeZipTest.zip';
$fileToZip = __DIR__.'/hello.txt';

$zip = new ZipArchive();
if (true !== $zip->open($destination, ZipArchive::OVERWRITE)) {
  die("Problem opening zip $destination");
}
if (!$zip->addFile($fileToZip, basename($fileToZip))) {
  die("Could not add file $fileToZip");
}
echo "numfiles: " . $zip->numFiles . "\n";
echo "status: " . $zip->status . "\n";
$zip->close()
like image 1
mlivan Avatar answered Oct 09 '22 00:10

mlivan