PHP ZipArchive不添加任何文件(Windows)

我甚至没有把一个文件放到一个新的zip文件中。

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(); 

该zip被创build,但是是空的。 然而没有错误被触发。

出了什么问题?

在某些配置上,似乎PHP在将文件添加到zip归档文件时无法正确获取localname ,并且必须手动提供此信息。 因此使用addFile()的第二个参数可以解决这个问题。

ZipArchive :: addFile

参数

  • 文件名
    要添加的文件的路径。
  • 的localName
    如果提供,这是ZIP档案中的本地名称将覆盖文件名。

PHP文档:ZipArchive :: addFile

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

您可能需要修改代码才能获得正确的树形结构,因为basename()将除去文件名之外的所有内容。

您需要在创建zip存档的文件夹中授予服务器权限。 你可以使用write permision创建tmp文件夹chmod 777 -R tmp/

还需要更改脚本试图找到hello.txt文件的目的地$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() 

选中此类将文件夹中的文件和子目录添加到zip文件中,并在运行代码之前检查文件夹权限,即chmod 777 -R zipdir /

 HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip'); <?php class HZip { private static function folderToZip($folder, &$zipFile, $exclusiveLength) { $handle = opendir($folder); while (false !== $f = readdir($handle)) { if ($f != '.' && $f != '..') { $filePath = "$folder/$f"; // Remove prefix from file path before add to zip. $localPath = substr($filePath, $exclusiveLength); if (is_file($filePath)) { $zipFile->addFile($filePath, $localPath); } elseif (is_dir($filePath)) { // Add sub-directory. $zipFile->addEmptyDir($localPath); self::folderToZip($filePath, $zipFile, $exclusiveLength); } } } closedir($handle); } public static function zipDir($sourcePath, $outZipPath) { $pathInfo = pathInfo($sourcePath); $parentPath = $pathInfo['dirname']; $dirName = $pathInfo['basename']; $z = new ZipArchive(); $z->open($outZipPath, ZIPARCHIVE::CREATE); $z->addEmptyDir($dirName); self::folderToZip($sourcePath, $z, strlen("$parentPath/")); $z->close(); } }