Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php zip files without directory tree

Tags:

php

I am creating script zipping files from an array.

/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //vars
    $valid_files = array();
    //if files were passed in...
    if(is_array($files)) {
        //cycle through each file
        foreach($files as $file) {
            //make sure the file exists
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //if we have good files...
    if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $zip->addFile($file,$file);
        }
        //debug
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

        //close the zip -- done!
        $zip->close();

        //check to make sure the file exists
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}

@Mysql connect

$files_to_zip = array();
while($row = mysql_fetch_assoc($shots)) {
 $files_to_zip[] = '/home/username/domains/example.com/public_html/components/items/images/item/' . $row["name"] . '_thb.' . $row["ext"];
}

if(isset($_POST['create'])){

    //if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive5.zip');

}

After form submitting zip is created, but there's full directory tree inside files. How to only zip files without directories?

Second thing: When I open zip in total commander - I can see directories and files. When I open it normally - zip is empty.

like image 823
ivoas Avatar asked Oct 25 '25 11:10

ivoas


1 Answers

The second argument to the addFile() method is the name of the file inside the zip. You're doing this:

$zip->addFile($file, $file);

So you're getting something like:

$zip->addFile('/path/to/some/file', '/path/to/some/file');

Which just copies the path from the source into the zip. If you want all the files to be in one dir in the zip, remove the path from the file name:

$zip->addFile($file, basename($file));

This will give you:

$zip->addFile('/path/to/some/file', 'file');

Note this won't work too well if you have files with the same name in different directories.

like image 184
Alex Howansky Avatar answered Oct 28 '25 02:10

Alex Howansky