How to create and download a zip file using PHP and Ajax

To create and download a zip file using PHP and Ajax, you can follow these steps:

  • Create a PHP script that generates the zip file.
  • Use Ajax to trigger the PHP script and download the generated zip file.

Here's an example implementation:

Step 1: Create a PHP script to generate and download the zip file (zip_generator.php)

<?php
// Ensure that this script is only accessible via Ajax request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Define the folder containing the files you want to include in the zip
    $sourceFolder = 'path_to_your_files/';

    // Create a unique filename for the zip file
    $zipFileName = 'generated_zip_' . date('YmdHis') . '.zip';

    // Initialize a zip archive
    $zip = new ZipArchive();
    
    if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        // Create and add files to the zip archive
        $files = glob($sourceFolder . '*');
        
        foreach ($files as $file) {
            $zip->addFile($file, basename($file));
        }
        
        $zip->close();

        // Set the appropriate headers for file download
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
        header('Content-Length: ' . filesize($zipFileName));

        // Output the zip file for download
        readfile($zipFileName);

        // Clean up by deleting the temporary zip file
        unlink($zipFileName);
    } else {
        echo 'Could not create zip file';
    }
} else {
    // If this script is accessed directly, deny access
    echo 'Access denied.';
}
?>

In the above script replace path_to_your_files/ with the actual path to the folder containing the files you want to include in the zip.

Step 2: Create an HTML page with Ajax (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create and Download Zip</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <button id="generateZip">Generate and Download Zip</button>

    <script>
        $(document).ready(function() {
            $('#generateZip').click(function() {
                $.ajax({
                    url: 'zip_generator.php',
                    type: 'GET',
                    success: function() {
                        // Ajax request was successful, and the zip file was generated.
                        // The file should be downloaded automatically due to the Content-Disposition header.
                    },
                    error: function() {
                        alert('Error generating zip file.');
                    }
                });
            });
        });
    </script>
</body>
</html>

In this HTML page, we include jQuery for the Ajax request. When you click the "Generate and Download Zip" button, it triggers the Ajax request to the zip_generator.php script.

Ensure that both index.html and zip_generator.php are in the same directory.

When you click the button, the zip file will be generated and downloaded to the user's computer.

Muhammad Alfaiz
Alfaiz 3 months ago
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x