Search code examples
phpphp-ziparchive

PHP ZipArchive Issue


it's the first time I'm using PHP to make ZIP archives. However, I am not getting any zip files even though no error is being outputted. I did echo $zip->close and it gave 1.

Can someone help me?

/* Create zip folder */
$zip = new ZipArchive();
$zipCreate = $zip->open("newarchive.zip", ZipArchive::CREATE);

if($zipCreate !== TRUE) {
    die("Zip folder creation failed");
}

$zip->addFile("test.txt", "test.txt");
$zip->addFile("helllo.txt", "helllo.txt");
$zip->close();

Solution

  • Maybe try this instead:

    <?php
    
    /* Create zip folder */
    $zip = new ZipArchive();
    $zipCreate = $zip->open("newarchive.zip", ZipArchive::CREATE);
    
    if($zipCreate !== TRUE) {
        die("Zip folder creation failed");
    }
    
    $directory = getcwd() . '/';
    
    $files = array('test.txt', 'helllo.txt');
    
    foreach($files as $file) {
        $zip->addFile($directory . $file, basename($file));
    }
    
    $zip->close();
    

    In the first argument of the addFile() method, provide the full path of your file name, and in the second provide a directory/location of your file with in the archive and that should do the trick.