'Why am I getting error "Failure to create temporary file" when trying to close a zip file?

Hello this is my first time posting here, I am not sure how this works but I have included my code below. I would greatly appreciate some help.

I am having trouble with closing my zip file. The markers (print statements) that I have created are being executed. I am only getting an error with $zip->close().

For reference, I have PHP Version 7.4.24 and am I using a Mac. When my colleague ran it on his Windows system, it executed.

This is the error that is displayed in my browser:

Warning: ZipArchive::close(): Failure to create temporary file: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/nameOfMyFolder/folderzip.php on line 55

<?php
// name of directory (folder)
$pathdir = "/Applications/XAMPP/xamppfiles/htdocs/nameOfMyFile/";
    
//name of zip file to be created when zipped
$zipcreated = "archive.zip";

// new zip class
$zip = new ZipArchive;

if (extension_loaded("zip")){
echo "Zip extension is loaded";
}

//phpinfo();
// PHP Version 7.4.24

// Create a zip file and open it, check if it worked
if($zip -> open($zipcreated, ZipArchive::CREATE ) == TRUE) {
    // Store the path into the variable
    // opendir opens a directory handle
    $dir = opendir($pathdir);
       
    while($file = readdir($dir)) {
        // is_file checks if specified file is a regular file
        
        echo $pathdir.$file;
        
        if(is_file($pathdir.$file)) {
            $zip -> addFile($pathdir.$file, $file);
            echo "File/s copied";
        } else {
            //echo "File not copied";
        }
            //echo "While executed";
    }
    echo "Out of while loop";
    $zip->close();
    //$zip -> ZipArchive::close();
    //zip_close(resource ($zip));
    //$zip -> getStatusString();
} else {
    die ("Can't open $zipcreated");
}
?>


Solution 1:[1]

I've refactored your code and it appears to be working now. Take note of how I used the "! not" condition so the code can exit quicker and it doesn't need to be nested.

<?php

$folder_to_archive = "/path/to/your/folder/";
    
$zip_file = "archive2.zip";

if (!extension_loaded("zip"))
    die("Zip extension could not be loaded" . PHP_EOL);

$zip = new ZipArchive;

if ($zip->open($zip_file, ZipArchive::CREATE) !== true)
    die('Could not create Zip File' . PHP_EOL);

$dir = array_diff(scandir($folder_to_archive), ['.','..']);

foreach ($dir as $file) {
    $full_filename = $folder_to_archive . $file;

    if (!is_file($full_filename)) 
        continue;

    $zip->addFile($full_filename, $file);
}
$zip->close();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jacob Mulquin