if(isset($_POST['submit'])){
if(!empty($_FILES['files']['name'])){
$Zip = new ZipArchive();
$Zip->open('uploads.zip', ZIPARCHIVE::CREATE);
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
$Zip->close();
}
else {
echo "no files selected";
}
}
这里有什么问题?我刚刚看过一个创建档案和添加文件的教程,但它不起作用......我使用的是PHP 5.4。它甚至没有给我任何错误。任何人都可以指导我在这里做错了什么。
以下是表格
<form action="" method="POST" enctype="multipart/form-data">
<label>Select files to upload</label>
<input type="file" name="files">
<input type="submit" name="submit" value="Add to archieve">
</form>
答案 0 :(得分:1)
这些行没有任何意义
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
在您发布的代码中,没有上传的文件被移动到uploads/
目录,并循环通过$_FILES["files"]
元素 - 这是一个包含各种值的关联数组,只有一个这是实际的文件名 - 并将每个值作为文件添加到ZIP,是荒谬的。 - 你应该阅读PHP docs relating to file uploading。很明显,你还不知道PHP如何处理文件上传,在尝试这样的事情之前你应该学习它。
一种解决方案是使用uploads/
将上传的文件移动到move_uploaded_file
目录,但是因为您只是真正使用该文件将其添加到存档,该步骤非常多余;你可以直接从临时位置添加它。首先,您需要对其进行验证,您可以使用is_uploaded_file
函数进行验证。
// Make sure the file is valid. (Security!)
if (is_uploaded_file($_FILES["files"]["tmp_name"])) {
// Add the file to the archive directly from it's
// temporary location. Pass the real name of the file
// as the second param, or the temporary name will be
// the one used inside the archive.
$Zip->addFile($_FILES["files"]["tmp_name"], $_FILES["files"]["name"]);
$Zip->close();
// Remove the temporary file. Always a good move when
// uploaded files are not moved to a new location.
// Make sure this happens AFTER the archive is closed.
unlink($_FILES["files"]["tmp_name"]);
}