Git Product home page Git Product logo

zipper's Introduction

Note

I haven't updated this package in a long time except merging PRs. The last time I was using this package was with PHP5. I archived the repository for the reason that I am no longer working with PHP (we all have to move on sometimes) and have no time to take proper care of it anymore.

Feel free to read the code, to fork it or to use it in whatever way you want.

Update 25th February 2020

I have merged a PR that includes a security fixe to mitigate zip directory traversal attacks.
This package is still archived and should be swapped out with another package.
However, as long as security fixes will come in I see it as my basic obligation to update this package on demand.

Zipper

Build Status

This is a simple Wrapper around the ZipArchive methods with some handy functions.

Installation

  1. Add this package to the list of required packages, inside composer.json
  • for Laravel 5: "chumper/zipper": "1.0.x"
  • for Laravel 4: "chumper/zipper": "0.5.x"
  1. Run composer update

  2. Go to app/config/app.php

  • add to providers Chumper\Zipper\ZipperServiceProvider::class
  • add to aliases 'Zipper' => Chumper\Zipper\Zipper::class

You can now access Zipper with the Zipper alias.

Simple example

$files = glob('public/files/*');
Zipper::make('public/test.zip')->add($files)->close();
  • by default the package will create the test.zip in the project route folder but in the example above we changed it to project_route/public/.

Another example

$zipper = new \Chumper\Zipper\Zipper;

$zipper->make('test.zip')->folder('test')->add('composer.json');
$zipper->zip('test.zip')->folder('test')->add('composer.json','test');

$zipper->remove('composer.lock');

$zipper->folder('mySuperPackage')->add(
    array(
        'vendor',
        'composer.json'
    ),
);

$zipper->getFileContent('mySuperPackage/composer.json');

$zipper->make('test.zip')->extractTo('',array('mySuperPackage/composer.json'),Zipper::WHITELIST);

$zipper->close();

Note: Please be aware that you need to call ->close() at the end to write the zip file to disk.

You can easily chain most functions, except getFileContent, getStatus, close and extractTo which must come at the end of the chain.

The main reason I wrote this little package is the extractTo method since it allows you to be very flexible when extracting zips. So you can for example implement an update method which will just override the changed files.

Functions

make($pathToFile)

Create or Open a zip archive; if the file does not exists it will create a new one. It will return the Zipper instance so you can chain easily.

add($files/folder)

You can add an array of Files, or a Folder and all the files in that folder will then be added, so from the first example we could instead do something like $files = 'public/files/';.

addString($filename, $content)

add a single file to the zip by specifying a name and the content as strings.

remove($file/s)

removes a single file or an array of files from the zip.

folder($folder)

Specify a folder to 'add files to' or 'remove files from' from the zip, example

Zipper::make('test.zip')->folder('test')->add('composer.json');
Zipper::make('test.zip')->folder('test')->remove('composer.json');

listFiles($regexFilter = null)

Lists all files within archive (if no filter pattern is provided). Use $regexFilter parameter to filter files. See Pattern Syntax for regular expression syntax

NB: listFiles ignores folder set with folder function

Example: Return all files/folders ending/not ending with '.log' pattern (case insensitive). This will return matches in sub folders and their sub folders also

$logFiles = Zipper::make('test.zip')->listFiles('/\.log$/i'); 
$notLogFiles = Zipper::make('test.zip')->listFiles('/^(?!.*\.log).*$/i'); 

home()

Resets the folder pointer.

zip($fileName)

Uses the ZipRepository for file handling.

getFileContent($filePath)

get the content of a file in the zip. This will return the content or false.

getStatus()

get the opening status of the zip as integer.

close()

closes the zip and writes all changes.

extractTo($path)

Extracts the content of the zip archive to the specified location, for example

Zipper::make('test.zip')->folder('test')->extractTo('foo');

This will go into the folder test in the zip file and extract the content of that folder only to the folder foo, this is equal to using the Zipper::WHITELIST.

This command is really nice to get just a part of the zip file, you can also pass a 2nd & 3rd param to specify a single or an array of files that will be

NB: Php ZipArchive uses internally '/' as directory separator for files/folders in zip. So Windows users should not set whitelist/blacklist patterns with '' as it will not match anything

white listed

Zipper::WHITELIST

Zipper::make('test.zip')->extractTo('public', array('vendor'), Zipper::WHITELIST);

Which will extract the test.zip into the public folder but only files/folders starting with vendor prefix inside the zip will be extracted.

or black listed

Zipper::BLACKLIST Which will extract the test.zip into the public folder except files/folders starting with vendor prefix inside the zip will not be extracted.

Zipper::make('test.zip')->extractTo('public', array('vendor'), Zipper::BLACKLIST);

Zipper::EXACT_MATCH

Zipper::make('test.zip')
    ->folder('vendor')
    ->extractTo('public', array('composer', 'bin/phpunit'), Zipper::WHITELIST | Zipper::EXACT_MATCH);

Which will extract the test.zip into the public folder but only files/folders exact matching names. So this will:

  • extract file or folder named composer in folder named vendor inside zip to public resulting public/composer
  • extract file or folder named bin/phpunit in vendor/bin/phpunit folder inside zip to public resulting public/bin/phpunit

NB: extracting files/folder from zip without setting Zipper::EXACT_MATCH When zip has similar structure as below and only test.bat is given as whitelist/blacklist argument then extractTo would extract all those files and folders as they all start with given string

test.zip
 |- test.bat
 |- test.bat.~
 |- test.bat.dir/
    |- fileInSubFolder.log

extractMatchingRegex($path, $regex)

Extracts the content of the zip archive matching regular expression to the specified location. See Pattern Syntax for regular expression syntax.

Example: extract all files ending with .php from src folder and its sub folders.

Zipper::make('test.zip')->folder('src')->extractMatchingRegex($path, '/\.php$/i'); 

Example: extract all files except those ending with test.php from src folder and its sub folders.

Zipper::make('test.zip')->folder('src')->extractMatchingRegex($path, '/^(?!.*test\.php).*$/i'); 

Development

Maybe it is a good idea to add other compression functions like rar, phar or bzip2 etc... Everything is setup for that, if you want just fork and develop further.

If you need other functions or got errors, please leave an issue on github.

zipper's People

Contributors

actionm avatar aldas avatar arthurprogramming avatar bart avatar berdyshev avatar bestmomo avatar bhavinjr avatar brujo-rojas avatar chumper avatar codepotato avatar dasraab avatar eughenio-westwing avatar francescoassenza avatar heslil avatar ikeedo avatar inov avatar lex111 avatar nadjib avatar nextlevelshit avatar plantwebdesign avatar rvitaliy avatar snipe avatar snoopysecurity avatar socieboy avatar thecotne avatar vool avatar xploseof avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zipper's Issues

Issues using 0.6.* in fresh Laravel 5 installation

Hy,
I made a fresh Laravel 5 installation.
I only included "barryvdh/laravel-ide-helper": "~2.0" and "Chumper/Zipper": "0.6.*"
and updated the app.php as described.
Now I got the following error:
image

I also find a small error in your installation description.
You made different installation hints for Laravel 4 / 5 by using 1a and 1b.
Since the location of the app.php has changed I could be helpful to use
2a (app/config/app.php) and 2b (config/app.php)

Thanx for developing the Zipper ;)

Service provider not deferred

The package method (called in boot) does a lot of file/directory checks when it is called. If you have an app that does a lot of things NOT related to Zipper this will cause a problem. Would it be possible to set the service provider to be deferred?

Feature request: Adding releases

Since I can't specify the release in my composer.json file and have to pull in the dev-master my code could easily break if you make any major changes to the package. It would be nice to be able to specify the package in its current state.

Read about GitHub Releases.

add functions ignored $rootDirInZip

Hi,

I noticed that the $rootDirInZip variable in the add function is replaced when it's set:
@ line 126:

if(!is_null($rootDirInZip)) $rootDirInZip = $this->currentFolder;

According to me the not operator should be removed:

if(is_null($rootDirInZip)) $rootDirInZip = $this->currentFolder;

More clarification please.

there are a couple of methods i just don't get , basicly when to use any of the below

addString($filename, $content)
close()
home()
zip($fileName) // does exactly the same as make ,so is it for ?

also i cant quite understand the main example ,do they all related to each other or each suppose to do something on its own ,am asking because they are using the same object so some lines doesn't make any sense.

Packagist needs a version

Hi

Any chance you could start using versions, even if it is 0.1.0? I'd like to ensure that when I do a composer install when I push my project to different servers that I'm getting the same version. At the moment we can only install the dev-master, which means I can never be sure it's the same version of files on different servers.

I don't know how hard it is to define version, so I don't know if this is a big task or not sorry.

Support for lumen

Hi does this package works with laravel lumen?
if no, is it possible to add support?

Chumper\Zipper\Zipper::make(): Cannot destroy the zip context

Cannot create the next structure
-zip
-folder
-subfolder
-file
-subfolder
-file
-file

The code is here:
$zip = storage_path() . '/app/downloads/' . $theme[ 'slug' ] . '.zip';

        $zipper->make( $zip )->folder( 'assets/css' )->add( storage_path() . '/app/assets/theme.css' );

        $zipper->zip( $zip )->folder( 'assets/js' )->add( storage_path() . '/app/assets/js.js' );
        $zipper->zip( $zip )->folder( 'assets/js' )->add( storage_path() . '/app/assets/app.js' );
        $zipper->zip( $zip )->add( storage_path() . '/app/user.1/' . $theme[ 'slug' ] . '/index.html' );

Call to a member function addFile() on null

Hi, thanks a lot for the package. I'm having some trouble zipping a set of four images. This is done by triggering the saved() event. However, when I do this:

SizeTexture::saved(function($st)
{
    $files = array($st['image_diffuse'], $st['image_nrm'], $st['image_spec'], $st['image_disp']);
    $zipper = new \Chumper\Zipper\Zipper;
    $path = realpath(public_path()) . '/uploads/textures/';

    // We'll create the zip even if we only have one image

    foreach ($files as $file) {
        if ($file != '') {
            $zipper->add($path . $file);
        }
    }

    $zipper->make('file.zip');
});

I get the following error:

Call to a member function addFile() on null

I'm not entirely sure that this is a problem with the plugin, because my $path points to the full path of the file in my disk, not as a web address (Something like h:\folder\public\uploads...). Do you have any clues?

Thanks in advance!

listFiles - Full list of methods for Zipper Documentation is missing

Chumper,

This library works awesome, thank you so much for building it!

I noticed "listFiles()" wasn't in your main documentation on the front, so I wanted to let you know what I dug up snooping around for that function so I could see what was inside of the ZIP file.

Great job again, we're going to use it in our Laravel Project.

-Nathan

make($pathToFile, $type = 'zip')
zip($pathToFile)
phar($pathToFile)
extractTo($path, array $files = array(), $method = Zipper::BLACKLIST)
getFileContent($filePath)
add($pathToAdd)
addString($filename, $content)
getStatus()
remove($fileToRemove)
getFilePath()
close()
folder($path)
home()
delete()
getArchiveType()
getCurrentFolderPath()
contains($fileInArchive)
getRepository()
getFileHandler()
getInternalPath()
listFiles()
__destruct()

Create own folder path in zip

When adding a file it's folder path is also created in the zip file.

I'm using this script to generate a zip containing files selected by the user... the user has no interest in how/where I store these files on the server. I think it's better to place a file in the zip's root (by default). When set, the $rootDirInZip should be relative to the zip's root.

Example:

Default
File: /path/to/folder/filename.pdf
Code: $zipper->add('/path/to/folder/filename.pdf');
Zip's content:
.
..
filename.pdf

* With $rootDirInZip*
File: /path/to/folder/filename.pdf
Code: $zipper->add('/path/to/folder/filename.pdf', 'test');
Zip's content:
.
..
test (dir)
test/filename.pdf

Code:

    /**
     * @param $pathToAdd
     * @param $rootDirInZip
     */
    private function addFile($pathToAdd, $rootDirInZip)
    {
        empty($rootDirInZip) ? $path = false : $path = true;

        $info = pathinfo($pathToAdd);
        $file_name = $info['filename'].'.'.$info['extension'];

        if(!$path)
            $this->zip->addFile($pathToAdd, $file_name);
        else
            $this->zip->addFile($pathToAdd,$rootDirInZip.'/'.$file_name);
    }

Does not support UTF-8 char file name

When the file name contain UTF-8 char, it can't not be found.

E.G.
zip file contains

  1. 新增.docx
  2. primary_chicken.xlsx

input:
dd(Zipper::make('./_.zip')->listFiles());

output:
array:1 [ 0 => "primary_chicken.xlsx" ]

.cpgz zile

Hi there,

im currently using Zipper to zip 8 CSV file exports. For some reason when my code is live on the server and i download the ZIP i cant actually open it but on my local server i can.

Ive noticed sometimes when i try to open the zip file it extracts another file which looks like this with a weird extension on the end: ZIPFILE.zip.cpgz. Which cant be opened also.

This is my code.

public function zipCSV()
{

    $zipper = new Zipper;
    $files = glob(storage_path().'/downloads/all/*');
    $filepath = storage_path().'/downloads/zips/Backup - '.date("d-m-Y").'.zip';
    $zipper->make($filepath)->add($files)->close();

    return $filepath;

}

any ideas im pretty stumped?

thank you

Error when opening the .ZIP file

Hello, I've managed to zip the file but I'm having this error when downloaded and trying to open it:

Archive: /home/alique/Downloads/24x7project5.zip
[/home/alique/Downloads/24x7project5.zip]
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
zipinfo: cannot find zipfile directory in one of /home/alique/Downloads/24x7project5.zip or
/home/alique/Downloads/24x7project5.zip.zip, and cannot find /home/alique/Downloads/24x7project5.zip.ZIP, period.

Does anyone know why this might be?

Thanks a lot before hand !

errors

Zipper::getFileContent('public/test.zip')
return NULL

Zipper::make('public/test.zip')->folder('comp')->remove('composer.lock')->close()
return NULL

Zipper::make('public/test.zip')->extractTo('public/_new/', ['comp'], Zipper::BLACKLIST) Undefined class constant 'BLACKLIST'

Zip don't include hidden files

Hi, i'm Laravel developer on linux.
I try to create a backup of my server, but Zipper don' include hidden files (.files)
How can i do?
I use this test code:

$zipper = new \Chumper\Zipper\Zipper;
$zipper->make('zipped.zip')->add(public_path)->close();

Thanks

Call to a member function addFile() on a non-object

Hello, I can use the package on local XAMPP, however, when I use it on the server, I am getting this error at line 365 (/vendor/chumper/zipper/src/Chumper/Zipper/Zipper.php)

$this->repository->addFile($pathToAdd, $this->getInternalPath() . $file_name);

how to fix this problem?

Subfolder

$zipper->folder("foldername")->folder("subfoldername")->add("file") not working. how to create subfolder or child folder?

addFromString ?

Is it possible to add a file to a zip from a string, similar to ZipArchives addFromString function ?

Not all files get zipped

Hi and thanks for this Zipper!

It works almost perfectly for me, I just encounter a little problem.

I would like to zip albums. So I need to zip the album cover and album songs.

So first I create the archive and add it the cover like this:

    $zipper->make($archive_name)
        ->add(array(
            $directory.$album_picture,
        ));

Then, I add the songs:

$songs = //$songs_infos;
foreach($songs as $song){

$converted_file_directory = $directory.$song->filename;

$zipper->make($archive_name)
    ->add(array(
    $converted_file_directory
));

}

Actually, it works fine except that I only got the last song in my archive..

For example, I want to zip an album which is composed by:
-cover
-song_1.mp3
-song_2.mp3

My zip is like:
-cover
-song_2.mp3

Sounds like the first song is erased and I don't know why...

Any solution?

Thanks in advance !

Add folder + subdirectories in windows environment

I am having trouble adding a folder to a zip archive on a windows machine. It adds the files from within the folder, but does not recurse through to subdirectories...

I think it may be to do with backslash / forward slash mixing, but I am not entirely sure.

Any ideas?

Create Empty Directory

Hello,
I think create directory is missing. I tried $zipper->folder("folder"); but its not worked because there is no added file. I also tried $zipper->folder("folder")->add(array());.

Issue with Laravel Facade

Hi Nils,

I'm using barryvdh/laravel-ide-helper and get "Class \Chumper\Zipper\Facades\Zipper is not found.". It seems that there is something wrong with the L4 Facade.

When I try to use your class like "Zipper::make('/tmp/test.zip')->folder('app/config')->add('app.php');" I get the following error:

Unknown class passed as parameter (Zipper.php line 71): if (is_subclass_of($type, 'Chumper\Zipper\Repositories\RepositoryInterface'))

Any idea? Thanks!

Made zip according to database file name

hyy, i have a many files in folder and i want to make a zip according to database data, can i manage that with Zipper
Like i have a folder upload which have many files example
file1,file2,file3,file4
and according to database
i want to make a zip of file1 and fil2 together and download the zip
How can i manage this ?
Please instruct me urgently, is this possible.

Call to a member function close() on a non-object

On line: 258 / Zipper.php ( @$this->repository->close(); )

My code:

$filePath = storage_path().'/dumps/20130912083517.sql';
$zipper->make('test.zip')->folder('public')->add($filePath);

or

$zipper->zip('test.zip')->folder('public')->add($filePath);

EDIT: after removing destructor works well..

composer and github have different files

composer and github have different files

for example:
github - Zipper.php

public function add($pathToAdd, $fileName = null)
{
    if (is_array($pathToAdd)) {
        foreach ($pathToAdd as $dir) {
            $this->add($dir);
        }
    } else if ($this->file->isFile($pathToAdd)) {
        if ($fileName)
            $this->addFile($pathToAdd, $fileName);
        else
            $this->addFile($pathToAdd);
    } else
        $this->addDir($pathToAdd);
    return $this;
}

composer ("chumper/zipper": "0.6.x") - github - Zipper.php

public function add($pathToAdd)
{
    if (is_array($pathToAdd)) {
        foreach ($pathToAdd as $dir) {
            $this->add($dir);
        }
    } else if ($this->file->isFile($pathToAdd)) {
        $this->addFile($pathToAdd);
    } else
        $this->addDir($pathToAdd);
    return $this;
}

Error: Your PHP version is not compiled with zip support

I'm getting this error with a Laravel project

Exception in ZipRepository.php line 23:
Error: Your PHP version is not compiled with zip support

The application is working perfectly on the local machine, but after it is deployed on a Godaddy hosting account, I'm getting this error.

How to fix it ?

ExtractTo Won't Create Directory

In the extractTo function there's a check if the directory exists and will create it if it does not. However, prior to that it calls realpath, which returns false if the directory does not exist.

Not extracting html, css or js files?

$zipper->make($request->file('zipfile'))->extractTo($directoryPath.$detailFolder);

This is the content of my ZIP:
image

And this is what actually gets extracted:
image

All the folders have files in them. Why might this be happening?

Multiple Errors with Laravel 4

Not sure what might be going wrong. I added the service provider to my config and yet

$zipper = new Zipper;

Yields an error on "undefined method make"

If I use

$zipper = new \Chumper\Zipper\Zipper

I receive an error on "fatal error cannot call each() on undefined"

If I copy and paste the "sample" code I get a failure on ->close() in the deconstructor

Any ideas what I'm doing wrong?

v0.6.1 isn't compatible with PHP 5.3.x

Minimum PHP required on packagist is listed as 5.3.0, but requires illuminate/support and illuminate/filesystem, both of which have 5.4.0 minimum requirements. Due to that code's use of [] array shortcuts, using v0.6.1 with PHP 5.3.x results in errors like this:

Parse error: syntax error, unexpected '[' in /path/to/app/vendor/illuminate/support/helpers.php on line 351

please create laravel 5 branch

i will fix all the bugs in laravel 5 branch
i have project that is in laravel 5 and i want to use this package

it will be grate if you add me in contributors or i will create pull requests

Strange behaviours

Hi,
I try to use this package in laravel. The code work correctly. The zip file it's created in public folder. But The request of download doesn't found The file.
At second request The download start regular.
Regards

Client download method?

Hi there,
I really like the package, but I was wondering if you could maybe make a function in order to download the zip package to the client

Thanks !

Zip doesn't create when removing source directory after zip make

I can successfully ZIP a folder of files. The problem is that when I try to delete the source directory after creating the ZIP (line 4 below), the ZIP doesn't get created. Is there a way to ensure the ZIP has been finalised before I delete the source directory?

$batch_path = storage_path().$this->batch_base.'/'.$batch_name;
$zip_path = 'downloads/invoices/'.$batch_name.'.zip';
Zipper::make($zip_path)->add($batch_path);
File::deleteDirectory($batch_path);

Getting error calling Zipper::make, "Call to a member function addFile() on a non-object"

"Error occured: Call to a member function addFile() on a non-object"

Got the above error after updating recently. Tracked it down to line 73 of the following lines of code in "Zipper.php":

71 $name = 'Chumper\Zipper\Repositories' . ucwords($type) . 'Repository';
72 if (is_subclass_of($name, 'Chumper\Zipper\Repositories\RepositoryInterface'))
73 $this->repository = $type;
74 else
75 $this->repository = new $name($pathToFile, $new);
76
77 return $this;

Changed it to the following code which works for me:

71 $name = 'Chumper\Zipper\Repositories' . ucwords($type) . 'Repository';
72 if (is_subclass_of($name, 'Chumper\Zipper\Repositories\RepositoryInterface'))
73 {
74 $this->repository = new $name($pathToFile, $new);
75 }
76 else
77 {
78 throw new Exception(sprintf('Repository class "%s" cannot be found.', $name));
79 }
80
81 return $this;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.