How can PHP be used to create a .zip file of a folder on a web server?
To create a .zip file of a folder on a web server using PHP, you can use the ZipArchive class which provides functions to create, open, and extract zip archives. You will need to recursively iterate through the files and folders in the directory you want to zip, adding them to the zip archive. Finally, you can save the zip file to a location on the server.
$folderPath = '/path/to/folder';
$zipFileName = 'folder.zip';
$zip = new ZipArchive();
if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderPath), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = realpath($file);
if (is_dir($file)) {
$zip->addEmptyDir(str_replace($folderPath . '/', '', $file . '/'));
} elseif (is_file($file)) {
$zip->addFile($file, str_replace($folderPath . '/', '', $file));
}
}
$zip->close();
echo 'Zip file created successfully.';
} else {
echo 'Failed to create zip file.';
}
Keywords
Related Questions
- How can PHP developers handle complex search queries that involve multiple criteria and search terms in a user-friendly manner?
- How can PHP developers ensure that their file paths are correctly configured when including files in their scripts on different environments?
- In PHP, what strategies can be employed to streamline and optimize code for user registration processes, such as generating passwords and sending confirmation emails?