tags:

views:

21

answers:

1

hi all, I'm trying to use php to create a zip file (which it does - taken from this page - http://davidwalsh.name/create-zip-php), however inside the zip file are all of the folder names to the file itself.

Is it possible to just have the file inside the zip minus all the folders?

Here's my code:

function create_zip($files = array(), $destination = '', $overwrite = true) {

    if(file_exists($destination) && !$overwrite) { return false; };
    $valid_files = array();
    if(is_array($files)) {
        foreach($files as $file) { 
            if(file_exists($file)) { 
                $valid_files[] = $file;
            };
        };
    };
    if(count($valid_files)) { 
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { 
            return false;
        };
        foreach($valid_files as $file) { 
            $zip->addFile($file,$file);
        };
        $zip->close();
        return file_exists($destination);
    } else {
        return false;
    };

};


$files_to_zip = array('/media/138/file_01.jpg','/media/138/file_01.jpg','/media/138/file_01.jpg');

$result = create_zip($files_to_zip,'/...full_site_path.../downloads/138/138_files.zip');
+2  A: 

The problem here is that $zip->addFile is being passed the same two parameters.

According to the documentation:

bool ZipArchive::addFile ( string $filename [, string $localname ] )

filename
The path to the file to add.

localname
local name inside ZIP archive.

This means that the first parameter is the path to the actual file in the filesystem and the second is the path & filename that the file will have in the archive.

When you supply the second parameter, you'll want to strip the path from it when adding it to the zip archive. For example, on Unix-based systems this would look like:

$new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile($file,$new_filename);
George Edison
thanks so much :)
SoulieBaby
Strange that this identical problem has cropped up twice in two days... http://stackoverflow.com/questions/3988496/how-to-add-a-txt-file-and-create-a-zip-in-php/3989210#3989210
Mark Baker
LOL popular question? strange.
SoulieBaby