PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
127: ZipArchive for Compression
You've probably hit a point in your project where you're dealing with too many individual files—maybe it's a set of user-uploaded documents or a bunch of daily logs—and you realize that sending 50 separate files over the wire or storing them loosely is a nightmare. That's where the ZipArchive class comes in. It's the standard way in PHP to bundle files together and compress them.
How do I actually create a zip file and put some files in it?
The most important thing to remember is that ZipArchive doesn't just "save" a file instantly. You open a handle to a zip file, add your items, and then you must call close(). If you forget close(), the file won't actually be written to disk, and you'll be left wondering why your zip folder is 0 bytes.
$zip = new ZipArchive();
$filename = "user_export_123.zip";
if ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
// Add a specific file: addFile(path_on_disk, name_inside_zip)
$zip->addFile('exports/report.pdf', 'report.pdf');
$zip->addFile('exports/data.csv', 'data.csv');
// You can even add strings as files if you don't have a physical file on disk
$zip->addFromString('readme.txt', 'This export was generated on ' . date('Y-m-d'));
$zip->close();
echo "Zip created successfully!";
} else {
echo "Failed to create zip.";
}
Is there a way to zip an entire folder without adding every file one by one?
Manually calling addFile() is fine for two or three items, but if you're zipping a directory of 500 images, you need a loop. PHP doesn't have a "zipFolder()" method out of the box, so we combine ZipArchive with a RecursiveIteratorIterator. I use this pattern all the time for backup scripts.
$zip = new ZipArchive();
$sourceFolder = 'uploads/user_assets/';
$destFile = 'backup.zip';
if ($zip->open($destFile, ZipArchive::CREATE) === TRUE) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourceFolder),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
// Skip directories (they are added automatically when files are added)
if (!$file->isDir()) {
// Get the real path to the file
$filePath = $file->getRealPath();
// We want the path inside the zip to be relative to the source folder
// Otherwise, the zip will contain the full absolute path of your server
$relativePath = substr($filePath, strlen($sourceFolder));
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
}
How do I extract a zip file back into a folder?
Unzipping is significantly simpler than zipping. You don't have to loop through files; you just tell PHP where the zip is and where you want the contents to land. One quick tip: make sure the destination folder has the correct write permissions, or extractTo() will fail silently or throw a warning depending on your error settings.
$zip = new ZipArchive();
$zipFile = 'incoming_data.zip';
$extractPath = 'temp/extracted_files/';
if ($zip->open($zipFile) === TRUE) {
// This extracts everything in the archive to the specified directory
$zip->extractTo($extractPath);
$zip->close();
echo "Files extracted to $extractPath";
} else {
echo "Could not open the zip file.";
}
📋 Practical Task
Build a Timestamped Log Archiver
Create a script that automates the archiving of a logs directory. Your script should perform the following steps:
- Define a source directory named
logs/(create a few dummy.txtfiles in there first). - Generate a filename for the zip archive that includes the current date and time (e.g.,
logs_archive_2023-10-27_1430.zip). - Use a
RecursiveIteratorIteratorto find all files within thelogs/folder and add them to the archive. - Ensure the files inside the zip maintain their relative structure (don't include the full server path).
- After the zip is successfully closed, use
unlink()to delete the original dummy text files from thelogs/folder to simulate a "cleanup" process.
There are no comments for now.