View Feed
group-icon
PHP Programmers
Community for PHP Programmers : Ask questions, doubts and help each other get better at PHP
218 Members
Join this group to post and comment.

Tutorial: Storing files and retrieving them as compressed files, using PHP & MySQL.

I had a requirement to do as getting a few parameters and according to them, compressing a set of files and give it to users for download. So, the best way would be compressing it into zip files. For those, who don't know what are zip files, you can see this definition, taken from WinZip's official website:
“Zip files (.zip or .zipx) are single files, sometimes called “archives”, that contain one or more compressed files. Zip files make it easy to keep related files together and make transporting, e-mailing, downloading and storing data and software faster and more efficient. The Zip format is the most popular compression format used in the Windows environment, and WinZip is the most popular compression utility.”
– winzip.com
Okay, as now we are clear in what we are doing, lets work on creating the application.
First and foremost, we need a MySQL Database, with the following tables. A simplified way is this:
select * from plugins;
+----+---------------+-----------------------------------+------------------+
| id | name          | desc                              | filename         |
+----+---------------+-----------------------------------+------------------+
|  1 | jQuery        | jQuery is a cross-browser JavaScr | jquery.js        |
|  2 | MooTools      | MooTools (My Object-Oriented Tool | mootools.js      |
|  3 | Scriptaculous | script.aculo.us is a JavaScript l | scriptaculous.js |
|  4 | PrototypeJS   | Provides class-style Object Orien | prototypejs.js   |
|  5 | Lightbox 2    | Lightbox 2 is a simple, unobtrusi | lightbox2.js     |
+----+---------------+-----------------------------------+------------------+
select * from downloads;
+----+----------+----------+
| id | pluginid | username |
+----+----------+----------+
|  1 |        1 | Praveen  |
|  2 |        4 | Praveen  |
+----+----------+----------+
The queries for the same are as follows:
CREATE TABLE `download` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pluginid` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

CREATE TABLE `plugins` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `desc` varchar(255) NOT NULL,
  `filename` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

INSERT INTO `plugins` (`id`, `name`, `desc`, `filename`) VALUES
(
  NULL, 'jQuery', 'jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML.', 'jquery.js'
), (
  NULL, 'MooTools', 'MooTools (My Object-Oriented Tools) is a lightweight, object-oriented, web-application framework for JavaScript, written in JavaScript', 'mootools.js'
), (
  NULL, 'Scriptaculous', 'script.aculo.us is a JavaScript library built on the Prototype JavaScript Framework, providing dynamic visual effects and UI.', 'scriptaculous.js'
), (
  NULL, 'PrototypeJS', 'Provides class-style Object Oriented and AJAX, freely distributable under the terms of an MIT-style license.', 'prototypejs.js'
), (
  NULL, 'Lightbox 2', 'Lightbox 2 is a simple, unobtrusive script used to overlay images on the current page. It''s a snap to setup and works on all modern browsers.', 'lightbox2.js');

INSERT INTO `download` (`id`, `pluginid`, `username`) VALUES 
(
  NULL, '1', 'Praveen'
), (
  NULL, '4', 'Praveen'
);
Next part is the storing files. All the files (jquery.js, mootools.js, scriptaculous.js, prototypejs.js, and lightbox2.js) are stored under "plugins" folder. You should already have a code for the users to make it to the selection of the files. We use a session & user management here. If you see the second table, it tracks the downloads with their usernames. We get the username from a session variable.

Now there should be a dedicated folder for creating the zip file, with the permissions set to 777 (*nix) or write permissions (Windows). Lets have the name of the folder as "downloads".
The final part is the writing of the core logic, which creates the compressed files for downloads.

Let us now write the core PHP function, which creates the zip files.
function create_zip($files = array(), $destination ''$overwrite false)
{
    
//if the zip file already exists and overwrite is false, return false
    
if (file_exists($destination) && !$overwrite)
    {
        return 
false;
    }
    
//vars
    
$valid_files = array();
    
//if files were passed in...
    
if (is_array($files))
    {
        
//cycle through each file
        
foreach($files as $file)
        {
            
//make sure the file exists
            
if (file_exists($file))
            {
                
$valid_files[] = $file;
            }
        }
    }
    
//if we have good files...
    
if (count($valid_files))
    {
        
//create the archive
        
$zip = new ZipArchive();
        if (
$zip - > open($destination$overwrite ZIPARCHIVE::OVERWRITE ZIPARCHIVE::CREATE) !== true)
        {
            return 
false;
        }
        
//add the files
        
foreach($valid_files as $file)
        {
            
$zip - > addFile($file$file);
        }
        
//debug
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
        //close the zip -- done!
        
$zip - > close();
 
        
//check to make sure the file exists
        
return file_exists($destination);
    }
    else
    {
        return 
false;
    }
}
After this, you have to include the file in your application, by either putting it on the top or including it in a separate file named functions.inc or something. I am using the second method as I have grouped all the functions in a single file. My code now as follows:
include("db.inc");
include(
"functions.inc");
// Since the user is logged in, the username is stored in $_SESSION["username"], which is "Praveen".
$res mysql_query("SELECT `filename` from `download`, `plugins` WHERE `plugins`.`id`=`download`.`pluginid` AND `username`='" $_SESSION["username"] . "'");
while(
$dat mysql_fetch_array($res))
    
$files[] = $dat[0];
create_zip($files$locationFilenametrue);
echo 
'[url='.$locationFilename.'] Click here to download PDFs [/url]';
That's it! The link to the freshly created zip file is displayed! 😀 Enjoy! If you have any queries, post them in this thread and I will do my best to answer them.
Sada, AbraKaDabra, The_Big_K, Issue, godfather, Mr.Don, narayana murthy, durga, Reya, Peter Kennedy, Dancer_Engineer Did you guys check this out? Try it out and do say... 😀

Share this content on your social channels -