判断一个压缩包中的目录层次,如果有多次文件夹就警告错误。
这里用到了三个方法,即:读取Zip目录结构、删除原有或指定的文件夹(目录)、判断指定目录是不是有子目录类。
主要用到的是require_once "File/Archive.php"; 另外就是自己写的后两个方法。
define("ZHOZ_TMP_DIR", "home/zhoz/temp_upload");
$file_name = "./zhozcom.zip";
require_once "File/Archive.php";
$source = File_Archive::read($file_name);
// 读取目录结构
$directory_name_list = array();
while($source->next()) {
if ((preg_match_all("/^([\w\-\.]+)\/([\w\-\.]+)$/", $source->getFilename(), $tmp))) {
if (!in_array($tmp[1], $directory_name_list)) {
array_push($directory_name_list, $tmp[1]);
}
}
}
if (count($directory_name_list) > 0) {
// 以前存在的目录删除
foreach ($directory_name_list as $tmp) {
if (is_dir(ZHOZ_TMP_DIR . "/" . $tmp[0])) {
ZhozHandler::delFileDir(ZHOZ_TMP_DIR . "/" . $tmp[0]);
error_log($tmp[0] . "
}
}
// 解压文件
$command = "unzip -o " . UPLOAD_TMP_DIR . "/". $file_name . " -d " . ZHOZ_TMP_DIR;
error_log($command, 0);
exec($command);
foreach ($directory_name_list as $tmp_dir) {
// 存在子目录
$zip_dir = ZhozHandler::checkNextDir(ZHOZ_TMP_DIR . "/". $tmp_dir[0]);
error_log($tmp_dir[0] . "
if ($zip_dir) {
$check_flg = true;
error_log($tmp_dir[0] . "
}
}
} else {
// 没找到目录也返回
$check_flg = true;
error_log("countdir----------is-----null", 0);
}
$command = "chmod -R 777 " . ZHOZ_TMP_DIR;
error_log($command, 0);
exec($command);
// ファイル削除
if (is_file(UPLOAD_TMP_DIR . "/". $file_name)) {
unlink(UPLOAD_TMP_DIR . "/". $file_name);
}
PHP删除指定的文件夹
下面这两个方法,将包含在ZhozHandler类中:
function delFileDir($dir) {
$dh=opendir($dir);
while ($file=readdir($dh)) {
if($file!="." && $file!="..") {
$fullpath = $dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
} else {
ZhozHandler::delFileDir($fullpath);
}
}
}
closedir($dh);
if (rmdir($dir)) {
return true;
} else {
return false;
}
}
判断是不是有子目录的方法:
function checkNextDir($directory) {
if(!is_dir($directory)) {
return true;
}
$handle = opendir($directory);
while (($file = readdir($handle)) !== false) {
if ($file != "." && $file != "..") {
if(is_dir($directory.'/'.$file)) {
return true;
}
}
}
closedir($handle);
return false;
}