How can PHP be used to create ZIP files directly on the server?

To create ZIP files directly on the server using PHP, you can utilize the ZipArchive class which provides methods for creating, adding files to, and closing ZIP archives. This allows you to dynamically generate ZIP files based on specific content or files stored on the server.

// Create a new ZIP archive
$zip = new ZipArchive();
$zipFileName = 'example.zip';

if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
    // Add files to the ZIP archive
    $zip->addFile('file1.txt');
    $zip->addFile('file2.txt');
    
    // Close the ZIP archive
    $zip->close();
    
    echo 'ZIP file created successfully!';
} else {
    echo 'Failed to create ZIP file';
}