Secure Internet File-Sharing with PHP, MySQL, and JavaScript

recently got fed up with using the usual shared-directories mechanism to implement file sharing. Not only are there too many permissions to define at the administrator level, it also requires all the actions for sharing files among different operating systems. And what if you have just an Internet connection? Sure you can use email or FTP, but those aren’t exactly elegant solutions.

I finally made up my mind to use PHP instead. I wrote a PHP file-sharing program that did all this:

  • Uploads and downloads files with a browser
  • Stores these files with metadata on a relational database management system (RDBMS)
  • Encrypts and compresses files when possible
  • Organizes the files, avoiding a hierarchical approach (directories) and preferably tagging them with labels and grouping them in a very different way

When I had the basic program completed, I wanted to upgrade it using these optimization guidelines:

  • Write fewer lines of code.
  • Use a popular RDBMS.
  • Separate the HTML code and, if possible, delegate it to someone who is more expert than I am.
  • Shorten the workflow of interactions with JavaScript pop-ups without mixing languages.

This article presents my optimized PHP program as a practical example for file sharing on Internet. It demonstrates how to integrate open source libraries and frameworks, use a database abstraction layer, and decouple application logic from the presentation. While not the most elegant implementation of the MVC (Model Control View) paradigm, it does show how the integration of different open source helper packages works and how these can make your life easier.

What You Need
A running Apache 2.X instance with a PHP 5.X module
A RDBMS database supported by PHP (The example uses MySQL 4.X)
PEAR
The Smarty package
The overLIB package
An Internet connection

Installation Instructions for a Quick Start
The server infrastructure for the example program requires a web server that can run PHP code, and the PHP interpreter has to be compiled with the support of the selected RDBMS. In my case, I chose the LAMP framework: Linux (Debian), Apache, MySQL and, obviously, PHP. The following installation instructions assume you have working installs of Apache 2.X, PHP 5.X, and MySQL 4.X, as well as an Internet connection.

To begin, download the accompanying source code for this article, and extract the file_sharing.zip file under the web server documents root (from now on [document_root]) with the following command:

unzip file_sharing.zip

PEAR MDB2 Installation
The installation of PEAR packages requires an installer that you already have available if you installed PHP version 4.3.0 or higher. If so, you just run this on the command line:

pear install MDB2pear install MDB2#mysql

Smarty Installation
To install the Smarty template engine (more on Smarty later), run the following if you are a Debian user:

apt-get install smarty

If you use another Linux system, take the following steps:

  1. Download the latest version of Smarty.
  2. Extract it under any directory you chose (e.g., /usr/local). This example will use [installation_dir] going forward.
  3. Create the directories [installation_dir]/smarty/templates_c and [installation_dir]/smarty/cache.

overLIB Installation
Here are the steps to install the overLIB JavaScript library (more on overLIB later):

  1. Download the overLIB zip file.
  2. Go to the [document_root] directory and run the following commands:
      mkdir overLIB  cd overLIB
  3. Extract the overLIB zip file.

MySQL Installation
Create your MySQL database schema with this command:

mysqladmin –u[user] –p[password] 

Setting Configuration Variables
As the file inc.config.php in the source code download explains, there are global variables specific to local installation. Set these variables as suggested in Table 1 below.

Table 1. Suggested Settings for Configuration Variables: These are global variables specific to local installation.
Value Value
$smarty_include_path [installation_dir]/smarty/libs
$pear_include_path where PEAR installation copies MDB2.php file
$overlib_path /overLIB
$template_dir [document_root]/file_sharing/smarty/templates
$config_dir [document_root]/file_sharing/smarty/configs
$cache_dir [installation_dir]/smarty/cache
$compile_dir [installation_dir]/smarty/templates_c
$dsn mysql://db_user:[email protected]_server/file_sharing

When all the above installations are complete, you can call http://yourserver/file_sharing/file_sharing.php (see Figure 1) and start to upload files (see Figure 2).


Figure 1. File-Sharing Application Home Page: This figure shows the uploaded and tagged files with the list of used tags.
 
Figure 2. File-Sharing Action Pop-Up: This figure shows the pop-up opened after clicking on a file.

Author's Note: Versions 6 and 7 of Internet Explorer send the inner text of a button instead of its value, which is counter to the W3C recommendation. So if you would like to use these IE versions for this example, you have to replace all

Let's Dive into the Code
PHP code is the glue of this example. Under the application root directory in the source code, there are four PHP files. The main one is file_sharing.php, and I chose to name all the others included by it as inc.*.php.

I put all the global variables specific to my local installation in inc.config.php. This means that after you extract the zip file in the downloadable source code, you can adapt it to your environment by appropriately setting the variables in this file.

The inc.vars.php file contains a PHP session-starting mechanism (used here only to pass through tag- and file-sorting method properties), some other global variables for convenience, and global assignments that are valid for all Smarty templates.

The inc.util.php file contains some utility functions, which are mostly a way to reduce the number of code lines. Some routines implement database access and are noteworthy as examples of using a database abstraction layer. These functions use the PEAR MDB2 API to access MySQL. (The next section offers a more detailed description of the advantages of this approach, with some examples of implementation.)

The file_sharing.php file is the core file that processes all HTTP requests and parses the variables passed by GET or POST methods. After parsing the action, the program retrieves all the data needed to manage the event, assigns that data to the Smarty structure, and then displays it.

Database Abstraction with PEAR
PEAR is a large repository of PHP libraries (called packages) that can speed up PHP development. In this program, the main PEAR package is the MDB2 library, which is the latest solution for database abstraction. Although I use the MySQL database in this example, you can run this solution in other environments (for example, in enterprises where Oracle is the database) by making only a few changes to the code. To use another database after installing the relative PEAR component for MySQL, all you need to do is change the value of the $dsn variable in inc.config.php. This variable must contain a valid Data Source Name (DSN) according to the rules described in the DSN documentation.

The DSN I used for MySQL is:

$dsn = 'mysql://user:[email protected]_server/mysql_db_name

This means all the calls to the database are perfectly transparent with regard to the underlying database.

Note that if you want to use another database in place of MySQL you have to create the same database schema. Of course, the file file_sharing.sql would not be valid anymore, but it would contain the SQL statements you have to translate in order to configure the database using another RDBMS.

Encrypting Files for Security
The file-sharing example allows the user to save files optionally in encrypted form, using the 128-bit-key AES (Advanced Encryption Standard) algorithm and saving passphrases in encrypted form (using SHA1 160-bit checksums as described in the RFC 3174 Secure Hash Algorithm). All the operations on encrypted files require these passphrases, so remember these important guidelines:

  • If you lose a passphrase, you can no longer download the file and you have to delete it with MySQL commands. Moreover, the data and passphrase travel through the Internet in clear form. A helpful upgrade would be to encrypt data and hash passwords locally with JavaScript functions before sending them over the Net.
  • If you want to use another database in place of MySQL, you have to replace the MySQL functions used for encrypting and hashing in the PHP code with equivalent ones.

What Smarty Is and How It Works
The technical description of Smarty is a template engine. Basically, it is a framework that helps developers easily maintain a standard site layout and separate logic from presentation. While many online discussion forums hold debates about whether or not Smarty is a valid minimum implementation of the MVC paradigm, I consider it a loophole for less experienced developers to achieve the separation between code and presentation.

Smarty itself is a programming language with basic syntax?some of the above-mentioned discussions are just about the need for a presentation engine to have its own logic. My opinion is that a business logic and a presentation logic both exist, and you might as well acknowledge both even if it is not a good idea to abuse the latter. In fact, PHP code has to deal as much as possible with the final variable assignments, and ultimately Smarty templates must remain HTML files.

To install Smarty, you must create two directories (templates and configs). Normally, you should place these two folders outside the web server document root, but in this example I put them under the application root (smarty/templates and smarty/configs). In the smarty/templates directory, I collect all Smarty files with .tpl extensions. After all, Smarty files are just HTML files whose content is assigned and passed by PHP code.

As previously stated, Smarty also has a basic syntax that is useful for lightly managing presentation logic. One useful construction is {include ...}, which allows you to embed common parts of templates in a master one. I adopted the same naming schema for PHP files, using the suffix inc for files representing partial parts of HTML pages. This modular mechanism requires you to write down page layouts before starting to write Smarty/HTML templates. For example, the schema in Figure 3 is the one the example uses for the pages files.all.tpl and files.tag.tpl. The organization and naming rules of the Smarty files reflect this schema.

Figure 3. Templates Layout Schema: The organization and naming rules of the Smarty files reflect this schema.

To see if Smarty really works, let's analyze the passing of an indexed array of associative arrays from PHP to Smarty. In particular, the function files in inc.util.php deal with the listing of files stored in the database. In the line $file_array=db_query($dsn,$sql), $file_array is the indexed array returned by SQL query; every element is a row that is an associative array with keys equal to the query fields. A bit further in the code, you will find lines that fill the Smarty structure. One of these is:

$smarty->assign('file_array', $file_array);

At the end, you find:

$smarty->display('files.all.tpl');

These instructions transfer to Smarty the control that renders HTML pages according to the rules in file files.all.tpl. This file embeds inc.file_list.tpl, where you will find the following lines:

    {foreach item=file from=$file_array name=file_loop}
  1. {if isset($file.protection)} ... ...

You can easily identify some syntax constructions, such as {foreach ... }, that cycle on the indexed arrays. You also can see the way to refer to elements in associative arrays: {$file.protection} corresponds to $file['protection'], and {$file.id} corresponds to $file['id'].

overLIB and Pop-Up Menus
The workflow process can be too long sometimes if PHP code has to process every action on the server side. JavaScript pop-ups are a solution for shortening the interactions a little bit, but inserting JavaScript in a configuration can produce unacceptable entropy and significantly decrease the separation between business and template logic. Smarty embeds a very useful and powerful JavaScript library called overLIB. According to its website, overLIB "is a JavaScript library created to enhance websites with small popup information boxes."

Smarty integrates overLIB with a very simple construction, {popup ... }. In the file inc.file_list.tpl, there is an example of overLIB use:

{include file='files.pop.tpl' assign='filePop'}...{popup     trigger=onClick    width=360    sticky=true     caption='Action'    closeclick=true    text=$filePop}>{$file.filename}... 

In this code snippet, you see how you can attach an overLIB pop-up with a single instruction. You can set up all the overLIB parameters listed here and separate HTML code for pop-up in an another file, files.pop.tpl.

Beautify Your PHP Code
It is normally difficult to set a right indentation or good spacing rules during coding, and PEAR PHP_Beautifier can help a lot. Install it as follows:

pear install PHP_Beautifier

Then run this on the command line:

php_beautifier [some_file].php --output new_file.php

The new_file.php file produced will be rearranged with great improvement in readability.

Furthermore, PEAR provides a set of coding standards. With the mechanism of filters, for example, you can format your code accordingly by running this:

php_beautifier --filters "Pear()" [some_file].php --output new_file.php

Because HTML and CSS coding are not my strengths (you may have guessed that already), I looked for a method to separate presentation from logic in a small Internet file-sharing application so I could easily delegate the presentation to an experienced graphic designer. The result was a practical example of using a database abstraction layer and separating HTML design from PHP programming using open source libraries and frameworks. You can leverage my example to create an Internet file-sharing application that lets your users securely share files and classify them with tags and metadata.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Related Posts