How can errors be effectively handled when zipping folders using PHP?

When zipping folders using PHP, errors can be effectively handled by checking for any errors during the zipping process and displaying an error message if any occur. This can be done by using the ZipArchive class in PHP, which provides methods for adding files to a zip archive and handling any errors that may occur.

$zip = new ZipArchive();

$zipFileName = 'example.zip';
$zip->open($zipFileName, ZipArchive::CREATE);

$folderToZip = 'path/to/folder';

if (is_dir($folderToZip)) {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderToZip), RecursiveIteratorIterator::SELF_FIRST);
    
    foreach ($files as $file) {
        if (!$file->isDir()) {
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($folderToZip) + 1);
            $zip->addFile($filePath, $relativePath);
        }
    }

    $zip->close();
    echo 'Folder successfully zipped.';
} else {
    echo 'Error: Folder not found.';
}