<?php
// Set the directory to be compressed
$directory = __DIR__; // Current directory (you can change this to any other directory path)

// Set the name of the output ZIP file
$zipFileName = 'website_backup.zip';

// Create a new ZIP file
$zip = new ZipArchive();
if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
    // Function to recursively add files to the ZIP archive
    function addFilesToZip($folder, $zip, $relativePath = '') {
        $files = scandir($folder);
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $filePath = $folder . DIRECTORY_SEPARATOR . $file;
            $localPath = $relativePath . $file;

            if (is_dir($filePath)) {
                // Add directory recursively
                $zip->addEmptyDir($localPath);
                addFilesToZip($filePath, $zip, $localPath . '/');
            } else {
                // Add file to the ZIP archive
                $zip->addFile($filePath, $localPath);
            }
        }
    }

    // Add the files to the ZIP archive
    addFilesToZip($directory, $zip);

    // Close the ZIP file
    $zip->close();

    // Send the ZIP file to the browser for download
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
    header('Content-Length: ' . filesize($zipFileName));
    readfile($zipFileName);

    // Delete the ZIP file from the server after download
    unlink($zipFileName);
    exit;
} else {
    echo 'Failed to create ZIP file.';
}
?>
