Mafika
Mafika

Reputation: 21

how to create a zip file from a folder - php

I have a problem.

I searched the internet for a solution, but nothing works well. I'm trying to make a script that will take files from a folder and threw them into a zip archive. But it doesn't work ..

I tried through different paths, but it's only me mixed up and nothing came of it.

Here is the current code that is according to me the easiest and should workbut doesn't do that ..

Can you help me?

function archivebackup(){
    $zip = new ZipArchive;
    if ($zip->open('Mail.zip', ZipArchive::CREATE) === TRUE){

        foreach (new DirectoryIterator('Mails/') as $fileInfo) {
            $fileName = $fileInfo->getFilename();
            // echo $fileName ."<br>";
            $zip->addFile($fileName);
        }   

        $zip->close();
    } 
}

Upvotes: 0

Views: 4609

Answers (1)

apokryfos
apokryfos

Reputation: 40690

It seems you're not including files in your current working directory and getFilename() only returns a filename without a path.

Do the following:

function archivebackup(){
    $zip = new ZipArchive;
    if ($zip->open('Mail.zip', ZipArchive::CREATE) === TRUE){

        foreach (new DirectoryIterator('Mails/') as $fileInfo) {
            if (in_array($fileInfo->getFilename(), [ ".", ".." ]) { continue; }
            $fileName = $fileInfo->getPathname();
            $zip->addFile($fileName);
        }   

        $zip->close();
    } 
}

Upvotes: 1

Related Questions