using zipArchive addFile() will not add image to zip

Vance picture Vance · Mar 24, 2011 · Viewed 24.1k times · Source

I've been at this for a while. This actually worked one time, then never again. it simply does not create the zip file. The file does exist.

$zip = new ZipArchive();
$filename = "./test" . time() .".zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {      
    exit("cannot open <$filename>\n");
}

$thisdir = "$_SERVER[DOCUMENT_ROOT]/zip";
$zip->addFile($thisdir . "/trash-icon.png", "/gabage.png");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();

If I add something like

$zip->addFromString("testfilephp.txt", "#1 This is a test string added as testfilephp.txt.\n"); 

it creates the zip with the txt file in it.. but a no go for anytype of existing file.

Answer

JohnnyB picture JohnnyB · Jan 31, 2014

The ZipArchive::addFile() method accepts the path to the file as its first parameter, but not all paths are created equal. addFile() method silently rejects the file and you never know what went wrong. As can be derived from the question, an alternative approach would be:

// $zip->addFile($file);
$content = file_get_contents($file);
$zip->addFromString(pathinfo ( $file, PATHINFO_BASENAME), $content);

In addition to getting the code working, file_get_contents() also generates decent error messages.