Uncategorized

How to Zip and Unzip Files in PHP

Compressing files when transferring them over the Internet has many advantages. In most cases, the combined total size of all files in the compressed format decreases by a nice margin. This means you save some of your bandwidth and users also get faster download speeds. Once users have downloaded a file, they can decompress it at any time. In short, compression can make delivering files over the Internet much easier for both you and your visitors.

A factor that can discourage you from compressing files or make the process very tedious , the fact is that you might have to do it manually. Fortunately, PHP includes many extensions that deal specifically with file compression and extraction. You can use the functions available in these extensions to automatically zip files in PHP.

Reading: How to create a compressed zip file on php

In this tutorial you will learn how to zip and unzip (compress and extract) files in PHP into a zip archive. You will also learn how to delete or rename files in an archive without first extracting them.

  • Compressing single files in PHP
  • Compressing multiple files from a directory
  • Modify or overwrite archives
  • Extract content from an archive
  • Get more control over archives

Compress individual Files in PHP

PHP ZipArchive class has many properties and methods that can help you to compress and decompress all your files.

You can add files to your zip archive add individually or as a whole directory at once. In either case, the first step is to create a new ZipArchive instance and then call the open($filename, [$flags]) method. This method opens a new zip archive for reading, writing or other modifications. There are five valid values ​​for the optional $flag parameter, which determine how different situations are handled.

  • ZipArchive::OVERWRITE – This flag overwrites the content in archive the specified one if it already exists.
  • ZipArchive::CREATE – This flag will create a new archive if it doesn’t already exist.
  • ZipArchive ::EXCL – This flag will cause an error if the archive already exists.
  • ZipArchive::CHECKCONS – This flag tells PHP to do additional consistency checks on the archive and throw an error if they fail.
  • ZipArchive::RDONLY – This flag became available in PHP 7.4.3 and allows you to make an archive read-only to open mode.

You can refer to the documentation of this method to learn about different error codes returned by w earth if the file cannot be opened. If the ZIP file is successfully opened or created, the method returns true.

You must use different flag combinations in different situations to avoid unexpected results. For example, use the ZipArchive::OVERWRITE flag if you don’t care about the contents of an existing archive. A new archive will not be created if one does not exist with that specific name.

See also  How to Build a Website with User Accounts (Step by Step Tutorial)

You can use a combination of ZipArchive::OVERWRITE and ZipArchive::CREATE to overwrite an existing archive and create a new archive , if none exist with that particular name. Here’s an example:

If you use the ZipArchive::CREATE flag, you’ll find that it starts modifying an existing archive if one already exists. That might be what you actually want, but it can also have some unexpected consequences. You can use a combination of ZipArchive::CREATE and ZipArchive::EXCL to ensure you only work with archives that didn’t exist before.

Once you’ve successfully opened the archive, you can use the addFile($filename, $localname, $start, $length) method to add any file from a specified path to your archive. The $filename parameter is the path of a file that you want to add to the archive. The $localname parameter is used to assign a name to the file in order to store it in the archive. You can call addFile() each time you want to add a new file to your archive.

Once you have added all required files to the archive, you can simply call the close() method to close it and save changes.

Suppose you have a website that allows users to download font files for various fonts along with the license information for their use. Files like this are perfect examples of automated archiving with PHP. The code below shows you how to do just that.

We’ll start by creating a ZipArchive instance and then use the open() method to create our archive. The addFile() method adds our current .ttf font file and .txt license file to the archive.

See also: Cost to Develop a Marketplace App Like TaskRabbit

You should note that the original files were in the fonts/Monoton directory. However, the PHP code places them directly in the root of our archive. You can change the directory structure as well as the names of the files that are included in the archive.

Compress multiple files from a directory

Adding individual files to your archive can get tedious after a while. For example, you may want to create an archive of all .pdf or .png files in one directory. The addGlob($pattern, $flags, $options) method is very useful in this case. The only disadvantage of this method is that you lose control over the location of individual files in the archive. However, you can still influence the directory structure within the archive with the $options parameter. The options are passed in the form of an associative array.

  • add_path – The value you assign to add_path will be prepended to the local path of the file in the archive.
  • remove_path – The value you assign to remove_path will be used to remove a matching prefix from the path of various files being added to the archive.
  • remove_all_path – If you set the value of remove_all_path to true, everything but the name will be removed from the path of the file. In this case, the files are added to the root directory of the archive.
See also  15 Tips for Creating a Great Website Footer

It is important to remember that a path is stripped before the value specified in add_path is prepended.

The following code snippet illustrates the use of addGlob() and all of these options.

As usual, we start by creating a ZipArchive instance and then use the open() method to create our create archive. Also, each time we specify different values ​​for the add_path key in the $options array before calling the addGlob() method. This allows us to deal with a specific set of files at a time and provide appropriate archiving options.

In the first case, we iterate over all .jpg files in lights directory and place them in the light_wallpapers directory in the archive. Similarly, we loop through all .ttf files in the documents directory and then place them in a folder called font_files in our archive. Finally, we iterate over all the .jpg and .png files in our documents at once and merge them all together in the images directory.

As you can see, the values ​​in the $options parameter are useful for organizing the content inside the archive.

Modifying or overwriting archives

You can combine different ones Flags and options to achieve a specific file and directory structure within the archive. As I mentioned earlier, we can use the open() method to open a new or existing archive for reading and writing.

In this section, we will learn about the differences that arise due to different combinations of Resulting flags can be passed to the open() method and $options to the addGlob() method. Suppose there is no archive named compressed_files.zip and we execute the following code.

It takes all the image files from the files/images directory strong> and put it in the wallpapers directory in the root of the archive. The path of the image files in the archive would be wallpapers/files/images.

You can get rid of the original path of all images using the following options:

The image files are now stored directly in Background Images and the original image path is discarded.

As I mentioned before, ZipArchive::CREATE either creates a new archive or starts modifying one existing archive if it already exists. You will not receive any warnings when an existing archive is modified. This means if you run the code in this section to create the archive and then run it again after replacing the original options with new ones, you’ll get some unexpected results.

See also: Create a contact group or distribution list in Outlook for PC

The archive contains then a wallpapers directory with the subdirectories files/images and the images directly in the wallpapers directory. It can be a little confusing when you start, and it can make you wonder why the $options you set are not honored.

Always make sure you install ZipArchive Use ::CREATE |ZipArchive::OVERWRITE when you want to overwrite everything inside an archive if it already exists, but don’t want the code to throw errors if it doesn’t.

See also  How To Build A Website Similar to Canva

Think too since an empty file no longer exists, it is considered a valid archive since libzip 1.6.0.

Extract contents from an archive

The ZipArchive class has a method called extractTo($ destination, $entries) to extract the contents of an archive. You can use it to either extract everything in the archive or just some specific files. The $entries parameter can be used to specify a single filename to extract, or you can use it to pass an array of files.

An important point to remember is that you need to specify the correct path of the file within the archive in order to extract it. For example, in the previous section, we archived a font file named AlegreyaSans-Light.ttf. The file was saved inside the archive in a directory called font_files. This means that the path you need to specify in the $entries parameter would be font_files/AlegreyaSans-Light.ttf and not just AlegreyaSans-Light.ttf. p>

The directory and file structure is preserved during the extraction process and the files are extracted to their respective directories.

If you omit the second parameter, the method extracts all files in the archive.

Get more control over the archives

The ZipArchive class also has many other methods and properties that help you get more information about the archive before extracting all of its contents.

p>

You can count the number of files in an archive using the count() method. Another option is to use the numFiles property. They can be used to iterate over all files in the archive and extract only the ones you need – or you can do something else with them like remove them from the archive.

In the following example we are deleting all Files in the archive containing the word Italic. A similar code could be used to delete all files that do not contain a specific word. You could also iterate through these files and replace a specific word with something else.

In the code above, we use deleteName() to delete a single file. You can also use it to delete an entire directory.

A similar function renameName($oldname, $newname) can be used to rename any file in the archive. You’ll get an error message if a file named $newname already exists.

Final thoughts

We’ve covered a number of very useful methods of the ZipArchive class that perform automatic compression and extraction of files in PHP a breeze. You should now be able to compress individual files or a group of files at once based on your own criteria. Likewise, you should be able to extract any specific file from the archive without affecting other contents.

Using count() and numFiles you get more control over individual files and can rename them or delete them would be super easy. You should go through the documentation at least once to learn more about such features.

See also: The Definitive Guide: How To Make Your First Wireframe

.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button