18.26. Program: Unzip

The unzip.php program, shown in Example 18-5, extracts files from a ZIP archive. It uses the pc_mkdir_parents( ) function which is defined in Section 19.11. The program also requires PHP’s zip extension to be installed. You can find documentation on the zip extension at http://www.php.net/zip.

This program takes a few arguments on the command line. The first is the name of the ZIP archive it should unzip. By default, it unzips all files in the archive. If additional command-line arguments are supplied, it only unzips files whose name matches any of those arguments. The full path of the file inside the ZIP archive must be given. If turtles.html is in the ZIP archive inside the animals directory, unzip.php must be passed animals/turtles.html, not just turtles.html, to unzip the file.

Directories are stored as 0-byte files inside ZIP archives, so unzip.php doesn’t try to create them. Instead, before it creates any other file, it uses pc_mkdir_parents( ) to create all directories that are parents of that file, if necessary. For example, say unzip.php sees these entries in the ZIP archive:

animals (0 bytes)
animals/frogs/ribbit.html (2123 bytes)
animals/turtles.html   (1232 bytes)

It ignores animals because it is 0 bytes long. Then it calls pc_mkdir_parents( ) on animals/frogs, creating both animals and animals/frogs, and writes ribbit.html into animals/frogs. Since animals already exists when it reaches animals/turtles.html, it writes out turtles.html without ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.