Search code examples
phpzip

How use php to manipulate files inside zip files?


If I have some text files inside zip files, is it possible to manipulate this text files and change information inside this zip file?

For example, if I have the file test.txt inside test.zip, is it possible to open this text file and change the content and put other, the same as if I use fopen, fputs and fclose but all inside the zip?


Solution

  • Yes, you can! :)

    Like this:

    $zip = new ZipArchive();
    $zip->open('test.zip');
    
    // Read from file
    $contents = $zip->getFromName('test.txt');
    var_dump($contents);
    
    // Write to file
    $zip->addFromString('test.txt', 'foo bar');
    
    // Close (and re-pack) zip file. Don't miss that!
    $zip->close();
    

    Check the documentation of the ZipArchive class.