eHow Blog:
How To

How to Create Zip Files With PHP

When you need to offer a user many files as a download, a ZIP file is a natural way to do so. All modern operating systems handle ZIP files easily, and users know what to expect from them. In some cases, though, you may not be able to zip the files ahead of time, such as if you intend to include a license file with the archive. When this happens, don't worry, as PHP allows you to easily create ZIP archives programmatically and then offer them to the user.

Difficulty: Moderately Challenging
Instructions

Things You'll Need:

  • Files to zip Webserver with PHP and the ZIP extension installed PHP code editor
  1. Step 1

    Upload your files to your web server into a common directory. Make sure this directory cannot be directly accessed by users by placing it outside the "www" folder on your server. That way, PHP will still be able to access the files but browsers won't.

  2. Step 2

    Create a new PHP script called "zipdownload.php" that is accessible by the web server. Your scripts will redirect users to this page when they need to download the dynamic ZIP archive.

  3. Step 3

    Create a new ZipArchive object in zipdownload.php by writing "$zip = new ZipArchive();". This will create a new container for your ZIP files and assign it to a variable, named "$zip." Use the "$zip->open" method to create a particular ZIP file in your servers' temp directory. See the Resources section for more details.

  4. Step 4

    Add files to your new ZIP archive using the "$zip->addFromString" method. This will encode a new file and add it to the ZIP archive. Repeat this as many times as is necessary. See the resources for more details.

  5. Step 5

    Close the file when you have finished adding files to your ZIP archive using the "$zip->close" method. You may now mail it to users or output it to the browser using PHP's "readfile" function.

  6. Step 6

    Delete the archive when you have finished with it by calling the "unlink" function on the file.

Tips & Warnings
  • Before attempting these steps, you will need a strong working understanding of PHP and Object Oriented Programming (OOP). When sending files as attachments to users, remember that you need to send both Content-type and Content-disposition headers to users before printing the contents of the file.
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This

Computers Fans

Follow us

  • Computers
  • Computers
Get Free Computers Newsletters
eHow At Home
eHow At Home

Copyright © 1999-2010 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US † requires javascript

eHow Computers
eHow_eHow Technology and Electronics