Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Zip Laravel Package

nelexa/zip

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nelexa/zip
    

    No PHP extensions required—works purely via PHP core.

  2. First Use Case: Create a ZIP file and add a file:

    use Nelexa\Zip\ZipFile;
    
    $zip = new ZipFile();
    $zip->addFile('path/to/local/file.txt', 'destination/inside/zip/file.txt');
    $zip->save('output.zip');
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Creating ZIPs from Files/Folders:

    $zip = new ZipFile();
    $zip->addFile('file1.txt'); // Adds to root of ZIP
    $zip->addDir('folder/', 'folder_in_zip/'); // Recursively adds a directory
    $zip->save('archive.zip');
    
  2. Extracting ZIPs:

    $zip = new ZipFile('archive.zip');
    $zip->extract('destination_folder/');
    
  3. Updating Existing ZIPs:

    $zip = new ZipFile('existing.zip');
    $zip->addFile('new_file.txt', 'new_path/inside.zip');
    $zip->save(); // Overwrites existing file
    
  4. Streaming Large Files:

    $zip = new ZipFile();
    $zip->addStream('large_file.txt', fopen('large_file.txt', 'r'));
    $zip->save('streamed.zip');
    

Integration Tips

  • Laravel Storage: Use Storage::disk()->path() to dynamically resolve file paths:

    $zip = new ZipFile();
    $zip->addFile(storage_path('app/file.txt'), 'file.txt');
    $zip->save(storage_path('app/archive.zip'));
    
  • Queue Jobs for Heavy ZIPs: Offload ZIP creation to a queue job (e.g., ZipArchiveJob) to avoid timeouts:

    ZipArchiveJob::dispatch('large_folder/')->onQueue('zip');
    
  • Encryption: Enable AES encryption (WinZip-compatible) during creation:

    $zip = new ZipFile();
    $zip->setPassword('secure123');
    $zip->addFile('file.txt');
    $zip->save('encrypted.zip');
    
  • ZIP64 Support: Automatically handles large files (>4GB) via ZipFile::setZip64(true).


Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Large ZIPs (>100MB) may hit PHP’s memory_limit. Use ZipFile::setCompressionLevel(0) for speed (but larger files) or chunk processing.
    • Fix: Increase memory_limit in php.ini or stream files in chunks.
  2. Path Handling:

    • Relative paths in addFile() are resolved relative to the current working directory, not the script’s location.
    • Fix: Use absolute paths or chdir():
      chdir(base_path());
      $zip->addFile('app/file.txt');
      
  3. Overwriting Files:

    • save() overwrites the ZIP file by default. Use a temporary path first:
      $zip->save(sys_get_temp_dir() . '/temp.zip');
      rename(sys_get_temp_dir() . '/temp.zip', 'final.zip');
      
  4. Case Sensitivity:

    • ZIP entries are case-sensitive on Linux but not on Windows. Normalize paths:
      $zip->addFile('File.txt', strtolower('file.txt'));
      

Debugging

  • Verify ZIP Integrity: Use ZipFile::test() to check if a ZIP is valid before extraction:

    if (!$zip->test()) {
        throw new \RuntimeException('Invalid ZIP file');
    }
    
  • List Contents: Debug with getFiles() or getFileList():

    print_r($zip->getFileList());
    
  • Error Handling: Wrap operations in try-catch for ZipException:

    try {
        $zip->extract('folder/');
    } catch (\Nelexa\Zip\Exception\ZipException $e) {
        Log::error('ZIP error: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Compression: Override ZipFile::setCompression() to use BZIP2:

    $zip->setCompression(\Nelexa\Zip\ZipFile::CM_BZIP2);
    
  2. Pre/Post-Add Hooks: Extend ZipFile to log or modify files before adding:

    class CustomZipFile extends \Nelexa\Zip\ZipFile {
        protected function beforeAddFile($localPath, $archivePath) {
            // Example: Convert Markdown to HTML
            if (pathinfo($localPath, PATHINFO_EXTENSION) === 'md') {
                $content = file_get_contents($localPath);
                $content = Markdown::parse($content);
                file_put_contents($localPath . '.tmp', $content);
                $localPath = $localPath . '.tmp';
            }
            return [$localPath, $archivePath];
        }
    }
    
  3. Progress Callbacks: Use ZipFile::setProgressCallback() for large operations:

    $zip->setProgressCallback(function($current, $total) {
        Log::info("ZIP progress: {$current}/{$total}");
    });
    

Config Quirks

  • Temporary Files: The library uses sys_get_temp_dir() by default. Override with:

    $zip->setTempDir(storage_path('framework/views'));
    
  • Permissions: Ensure the target directory for extraction is writable. Use storage_path() or public_path() for Laravel:

    $zip->extract(storage_path('app/extractions/'));
    
  • PHP Version:

    • PHP 8.0+: Uses named arguments and attributes (e.g., #[ZipFile]).
    • PHP 7.4: Stick to procedural methods. Test compatibility with ZipFile::getSupportedMethods().
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony