我有一个这样的目录结构:
members/
login.php
register.php
我在windows机器中通过PHP ZipArchive压缩它们,但当我将其上传到linux主机并通过PHP提取时,它会将它们作为两个没有目录的文件:
members'login.php
members'register.php
我想在解压缩文件后在主机上拥有完整的目录结构。请注意,这个开箱代码在我的本地机器上运行时没有任何问题。这是关于windows和linux的东西吗?我该如何解决?
PHP实际上并没有提供提取ZIP(包括其目录结构)的函数。我在手册中的用户评论中发现了以下代码:
function unzip($zipfile)
{
$zip = zip_open($zipfile);
while ($zip_entry = zip_read($zip)) {
zip_entry_open($zip, $zip_entry);
if (substr(zip_entry_name($zip_entry), -1) == '/') {
$zdir = substr(zip_entry_name($zip_entry), 0, -1);
if (file_exists($zdir)) {
trigger_error('Directory "<b>' . $zdir . '</b>" exists', E_USER_ERROR);
return false;
}
mkdir($zdir);
}
else {
$name = zip_entry_name($zip_entry);
if (file_exists($name)) {
trigger_error('File "<b>' . $name . '</b>" exists', E_USER_ERROR);
return false;
}
$fopen = fopen($name, "w");
fwrite($fopen, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_filesize($zip_entry));
}
zip_entry_close($zip_entry);
}
zip_close($zip);
return true;
}
来源于此。
尝试DIRECTORY_SEPARATOR
而不是使用:
$path=$someDirectory.'/'$someFile;
使用:
$path=$someDirectory。DIRECTORY_SEPARATOR$someFile;
将您的代码更改为:
$zip=新ZipArchive
if($zip->open("module.DIRECTORY_SEPARATOR.$file[name]")===TRUE){
$zip->extractTo('module.DIRECTORY_SEPARATOR')
}
它将适用于这两种操作系统。
祝你好运,
问题解决了!以下是我所做的:我从php.net用户评论中将创建zip文件的代码更改为这个函数:
function addFolderToZip($dir, $zipArchive){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
$zipArchive->addEmptyDir($dir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories
if(($file !== ".") && ($file !== "..")){
addFolderToZip($dir . $file . "/", $zipArchive);
}
}else{
// Add the files
$zipArchive->addFile($dir . $file);
}
}
}
}
}
$zip = new ZipArchive;
$zip->open("$modName.zip", ZipArchive::CREATE);
addFolderToZip("$modName/", $zip);
$zip->close();
在主机中,我只写了以下代码来提取压缩文件:
copy($file["tmp_name"], "module/$file[name]");
$zip = new ZipArchive;
if ($zip->open("module/$file[name]") === TRUE) {
$zip->extractTo('module/');
}
$zip->close();
它创建了文件夹和子文件夹。唯一剩下的错误是,它也提取了主文件夹中所有子文件夹中的每个文件,因此子文件夹中每个文件都有两个版本。