1

I am using the following script to zip a directory and download its contents.

The problem I am running into is with large file sizes. Memory limitations on my server restrict me from downloading the content. I get a 503 error. The server is temporarily unable to service your request due to maintenance downtime or capacity problems.

For reference, the code is below:

<?php

$dir = 'dir';
$zip_file = 'file.zip';

// Get real path for our folder
$rootPath = realpath($dir);

// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();


header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);

?>

What modifications might I make to fix this issue?

Jason Chen
  • 2,487
  • 5
  • 25
  • 44
  • 1
    Well you can increase the memory limit for Php processes. This can be done by editing the php.ini configuration file or from within the Php script using init_set function – Nadir Latif Jul 21 '19 at 02:19
  • 1
    have you tried directly zipping the folder instead of opening an archive and adding files one by one ? – jeremy_nikolic Jul 21 '19 at 03:18

0 Answers0