How to use PHP to Upload Zip Files and Extract the contents
* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.
It’s pretty easy to upload any type of file with PHP and this applies equally to ZIP files but ZIP files are a bit unique as they contain other files and you might want to access these within your PHP code individually.
In this tutorial, we’ll demonstrate how to:
- Create an HTML form to upload a zip file.
- Process the uploaded zip file in PHP by extracting its contents.
- Filter files by type (e.g., images, PDFs, audio) and save them to specific directories.
- Address key security considerations when handling zip file uploads.
Why Upload and Extract Zip Files with PHP?
Uploading and extracting zip files is an efficient way to manage multiple files at once, especially in scenarios such as:
- Batch Content Upload: Upload and organize images, documents, or media for a website or application.
- File Archiving: Process large datasets from users while maintaining file type organization.
- Automation: Streamline repetitive tasks by categorizing files programmatically.
Step-by-Step Tutorial: PHP Upload Zip File and Extract
1. Create an HTML Form for Uploading the Zip File
We’ll start by building an HTML form that allows users to upload a zip file.
<!DOCTYPE html>
<html>
<head>
<title>Upload and Extract Zip File</title>
</head>
<body>
<h2>Upload a Zip File</h2>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<label for="zipfile">Select a zip file:</label>
<input type="file" name="zipfile" id="zipfile" accept=".zip" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
2. Process the Zip File in PHP
On the server side, we’ll use PHP to handle the uploaded zip file, extract its contents, and organize the files based on type.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['zipfile'])) {
// Define target directories for file types
$targetDirs = [
'images' => 'uploads/images/',
'pdfs' => 'uploads/pdfs/',
'audio' => 'uploads/audio/',
];
// Create directories if they don't exist
foreach ($targetDirs as $dir) {
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
}
// Handle the uploaded file
$zipFile = $_FILES['zipfile']['tmp_name'];
$zip = new ZipArchive();
if ($zip->open($zipFile)) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$fileName = $zip->getNameIndex($i);
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Determine the target directory based on file type
if (in_array($fileExt, ['jpg', 'png', 'jpeg', 'gif'])) {
$targetDir = $targetDirs['images'];
} elseif ($fileExt === 'pdf') {
$targetDir = $targetDirs['pdfs'];
} elseif (in_array($fileExt, ['mp3', 'wav'])) {
$targetDir = $targetDirs['audio'];
} else {
continue; // Skip unsupported file types
}
// Extract and save the file
$targetPath = $targetDir . basename($fileName);
copy("zip://$zipFile#$fileName", $targetPath);
}
$zip->close();
echo "Files extracted successfully!";
} else {
echo "Failed to open zip file.";
}
}
?>
3. Security Considerations
Handling uploaded files comes with potential risks. Follow these best practices to ensure security:
- Validate File Type: Check the file type and extensions before extracting files to prevent malicious code execution.
- Limit File Size: Restrict the size of uploaded zip files to prevent server overload.
- Use a Secure Upload Directory: Save uploaded files in directories outside the web root.
- Sanitize File Names: Remove special characters or use
pathinfo()
to validate file names. - Set Appropriate Permissions: Restrict permissions on uploaded files and directories.
Conclusion
Using PHP to upload, extract, and organize zip files is a powerful solution for managing batch uploads. By following this tutorial, you can efficiently sort file types and implement security measures to keep your application safe.