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

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)
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 under the web server documents root (from now on [document_root]) with the following command:


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:db_password@db_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:password@mysql_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:


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($} ... ...

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: {$} corresponds to $file['protection'], and {$} 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:
Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining