Search code examples
phpzipepub

Adding a file to a zip uncompressed with PHP


I'm looking at a tutorial for creating an ePub file. It states that the zip that contains the ePub book must contain a textfile called mimetype that "must be first in the zip file, uncompressed". The example he gives uses a commandline tool, I was wondering how I could do the same thing in PHP.

I assume it would be first in the zip file as long as its the first thing I add in the code, but how to add it to the zip uncompressed. Or am I misreading this?

Thanks in advance.


Solution

  • You cannot do that with the native PHP ZipArchive class. But PEAR::Archive_Zip can - if you use the ARCHIVE_ZIP_PARAM_NO_COMPRESSION parameter when adding that specifc file.

    A simpler solution would be to use a template. Create a stub zip file with your uncompressed "mimetype" entry (zip -0), then use that as temporary zip and afterwards just add new entries to it:

    file_put_contents("epub.zip", base64_decode("UEsDBAoAAAAAAOmRAT1vYassFAAAABQAAAAIABwAbWltZXR5cGVVVAkAA5adVUyQVx5PdXgLAAEE6AMAAAToAwAAYXBwbGljYXRpb24vZXB1Yit6aXBQSwECHgMKAAAAAADpkQE9b2GrLBQAAAAUAAAACAAYAAAAAAAAAAAApIEAAAAAbWltZXR5cGVVVAUAA5adVUx1eAsAAQToAwAABOgDAABQSwUGAAAAAAEAAQBOAAAAVgAAAAAA"));
    $zip = new ZipArchive();
    $zip->open("epub.zip");
    
    $zip->addFiles(...);
    

    (untested though)