Home > OS >  Zip file isn't created and not downloaded from temp directory outside public_html
Zip file isn't created and not downloaded from temp directory outside public_html

Time:12-01

I have a simple script that should create and download the zip files from the files in the directory.

For some reason, the file isn't created/downloaded and will need your expertise. This is the script.

$i=0;
while ($stmt->fetch()) 
{
    $dir = '../tmp/file-'.$nom.'.pdf';
    $file_names[] = str_replace('../tmp/', '', $dir);
    $i  ;
}
$stmt->close();

if (!empty($dir))
{
        
    $archive_file_name = '../tmp/files.zip';
    $zip = new ZipArchive();
    
    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
    }
            
    foreach($file_names as $files)
    {
        $zip->addFile($files, basename($files));
    }
    $zip->close();
    ob_clean();
        
    if (file_exists($archive_file_name)) {          
        header("Content-type: application/zip"); 
        header('Content-disposition: attachment; filename='.$archive_file_name);
        header("Content-length: " . filesize($archive_file_name));
        header("Pragma: no-cache"); 
        header("Expires: 0"); 
        readfile("$archive_file_name");

    } else {
        exit("Could not find Zip file to download");
    }           
}

Always got the Could not find Zip file to download.

The script is in

 /site.com/admin/script.php

the temp dir is

/tmp/`

both are outside the public_html. /tmp and /site.com are on same level

CodePudding user response:

Your current code looks like this.

foreach($file_names as $files)
{
    $zip->addFile($files, basename($files));
}
$zip->close();

If you want to check if your files are really added you can do this:

foreach($file_names as $path)
{
    if (!file_exists($path))
    {
        exit("File [$path] does not exist.";
    }
    if ($zip->addFile($path, basename($path)) === false) 
    {
        exit("File [$path] could not be added to the ZIP file" .
             ", the reason is: " . $zip->getStatusString());
    }
}
if ($zip->count() == 0) 
{
    exit("No files were added to the ZIP file");
}
$zip->close();
  •  Tags:  
  • php
  • Related