PHP操作ZipArchive实现文件上传下载功能
To implement file upload and download functionality using PHP and ZipArchive, follow these steps:
1. File Upload:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Select files to upload:</label>
<input type="file" id="file" name="files[]" multiple>
<br>
<input type="submit" value="Upload">
</form>
</body>
</html>
upload.php
) to process the uploaded files.
<?php
if (isset($_FILES['files'])) {
$files = $_FILES['files'];
$zip = new ZipArchive(); // Create ZipArchive object
$zipFileName = "uploaded_files.zip"; // Set zip file name
if ($zip->open($zipFileName, ZIPARCHIVE::CREATE) !== true) {
echo "Error creating zip file: " . $zip->getArchiveError();
exit;
}
foreach ($files['error'] as $key => $error) {
if ($error === UPLOAD_ERR_OK) {
$fileName = $files['name'][$key];
$tmpName = $files['tmp_name'][$key];
if ($zip->addFile($tmpName, $fileName) === false) {
echo "Error adding file to zip: " . $fileName;
}
}
}
$zip->close(); // Close zip file
if (file_exists($zipFileName)) {
// Download the zip file
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . $zipFileName);
header('Content-Length: ' . filesize($zipFileName));
readfile($zipFileName);
unlink($zipFileName); // Delete the temporary zip file after download
exit;
} else {
echo "Error creating zip file";
}
}
2. File Download:
<a href="download.php">Download Uploaded Files</a>
download.php
) to handle the file download.
<?php
$zipFileName = "uploaded_files.zip"; // Set zip file name
if (file_exists($zipFileName)) {
// Download the zip file
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . $zipFileName);
header('Content-Length: ' . filesize($zipFileName));
readfile($zipFileName);
unlink($zipFileName); // Delete the temporary zip file after download
exit;
} else {
echo "Uploaded file not found";
}
This setup provides basic file upload and download functionality using PHP and ZipArchive. You can enhance it by adding error handling, progress tracking, and more robust file management.