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.';
}