我正在创建一个文件来提取 zip 文件。代码片段检查文件扩展名是否为 .zip,然后检查文件是否已存在。如果没有,请提取存档。
if($fileExtension == "zip")
{
if(is_dir("unzips/".$fileName) == false)
{
move_uploaded_file($_FILES["file"]["tmp_name"],"temp/".$_FILES["file"]["name"]);
$zip = new ZipArchive();
$zip -> open("temp/".$_FILES["file"]["name"]);
for($num = 0; $num < $zip->numFiles; $num++)
{
$fileInfo = $zip->statIndex($num);
echo "Successfully Extracted: ".$fileInfo["name"];
$zip->extractTo("unzips/".$fileName);
echo "<br />";
}
zip_close($zip);
unlink("temp/".$_FILES["file"]["name"]);
}
else
{
echo $fileName." The ZIP archive file has already been unzipped";
}
}
else
{
echo "Only .zip files are allowed";
}
这是 index.php 的完整代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Unzipping Zip File</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><input type="submit" name="submit" value="Extract">
</form>
<?php
if(isset($_POST['submit']))
{
$array = explode(".",$_FILES["file"]["name"]);
$fileName = $array[0];
$fileExtension = strtolower(end($array));
if($fileExtension == "zip")
{
if(is_dir("unzips/".$fileName) == false)
{
move_uploaded_file($_FILES["file"]["tmp_name"],"temp/".$_FILES["file"]["name"]);
$zip = new ZipArchive();
$zip -> open("temp/".$_FILES["file"]["name"]);
for($num = 0; $num < $zip->numFiles; $num++)
{
$fileInfo = $zip->statIndex($num);
echo "Successfully Extracted: ".$fileInfo["name"];
$zip->extractTo("unzips/".$fileName);
echo "<br />";
}
$zip -> close();
unlink("temp/".$_FILES["file"]["name"]);
}
else
{
echo $fileName." The ZIP archive file has already been unzipped";
}
}
else
{
echo "Only .zip files are allowed";
}
}
?>
<br />
<p id="end note">Please return to main menu and download individually extracted files.</p>
</body>
</html>
目录结构如下所示: D:/MyWebs/extracting/index.php D:/MyWebs/extracting/unzips(包含解压缩文件夹的最终目的地) D:/MyWebs/extracting/temp(存储 zip 然后删除它们)