我无法将一个文件放入新的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文件被创建,但为空。但是没有触发错误。
怎么了?
似乎在某些配置中,PHP在向zip存档中添加文件时无法正确获取localname
,因此必须手动提供此信息。因此,使用addFile()
的第二个参数可能会解决这个问题。
ZipArchive:: addFile
参数
- 文件名
要添加的文件路径。- localname
如果提供,这是ZIP归档文件中的本地名称,它将覆盖文件名。
PHP文档:ZipArchive::addFile
$zip->addFile(
$fileToZip,
basename($fileToZip)
);
您可能必须调整代码以获得正确的树结构,因为basename()
将从路径中删除除文件名以外的所有内容。
您需要在创建zip存档的文件夹中给予服务器权限。可以创建具有写权限的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();
}
}