Online File Storage with PHP

In this tutorial, I will show you how easy it is to create an online file storage system with PHP. You will learn how to upload files with PHP and list them by scanning the "uploads" folder.

Introduction

Have you ever wished that you had a place to upload files while on the road? What if you're using a public terminal or someone else’s computer and cannot install any third party software for file transfer?
Wouldn't it be neat to just open a page in a browser, and upload your file with the click of a button?

There's plenty of file hosting sites already all around, but in this tutorial I will show you how to make your own. Here's what we will be creating:

Step 1 - Basic HTML

Let's get started. The first thing we need is an empty HTML document. I use XHTML 1.0 Transitional with ISO-8859-1 char set. If you prefer, and don't have any need for special characters, you can replace this with UTF-8 char set.

 1 2   3   4   5   6 Online file storage  7   8   9 10   11  

Ok, now that we have a basic HTML file, we have basically nothing :) So let's add some content. I'll wrap all the contents in a DIV element to help style the page with CSS. The Fieldset and Legend tags are perhaps somewhat rare, but they are the definite markup for organizing content into groups.

I've added a password field that we'll be using to shoo away unwanted uploaders, as we don't want strangers to fill up our file quota with random junk.

Note that in contrast to the standard everyday Form element, this one has the enctype set to multipart/form-data.
This is needed for POSTing files and must be here. I've set the action modifier to point to this very same file.
What that means is that once the form is submitted, the form data will be POSTed back to the same page.

The hidden MAX_FILE_SIZE field is for PHP and defines the maximum size (in bytes) that we can submit. This however won't override the MAX_FILE_SIZE setting in the php.ini file, so that will always be the one that determines the max size.

 1 2 
 3 

Online File Storage

 4   5 
 6  Add a new file to the storage  7 
 8   9 

 10 

 11 

 12 

 13 

 14   15 
 16 


If we open the file in a browser, now we will have a boring and plain html form. It will submit content to itself but won't know what to do with it.

We need a place to display the files that we've already uploaded; so add the following html inside the container div under the first fieldset.

 1 2 
 3  Previousely uploaded files  4 
 10   11 
 12 
 13 


Notice that the unordered list with the id "files" is empty. Don't worry about that right now as we will fill that section with the files in the server.

Step 3 - Add CSS and JS

I used jQuery to create the ability to toggle the visibility of certain file types without having to refresh the page.
This is purely optional and removing the JS will speed up the loading of the page somewhat. So let's add the following lines to the HEAD of the HTML file.

 1 2   5  

I'm loading the jQuery from an external source at runtime. Again if you prefer, you can change this so that the file is loaded from a local source with this line.

 1 2  

Loading the file directly from code.jquery.com ensures that we are using the latest version and saves our bandwidth on every page load, but if the code.jquery.com server would happen to be down or overcrowded, we might not get the file when we need it.

Create a new folder called style and create a new CSS file in it with the name style.css. This will be the file that tells the browser how we want the page to look. There's quite a lot of CSS here, but it's simple enough for anyone to follow.

Now the page should look something like the following.

 1 2 @CHARSET "ISO-8859-1";  3 4 body  5 {  6  background-color: #cddcec;  7  font-family: "Arial";  8  font-size: 11px;  9 }  10 11 div#container  12 {  13  width: 600px;  14  margin: 0px auto;  15  border: 1px solid #e6eef6;  16  background-color: #ffffff;  17 }  18 19 div#container h1  20 {  21  background-color: #4b75b3;  22  margin: 0px;  23  padding: 8px;  24  font-family: "Arial";  25  font-weight: normal;  26  border: 1px solid #3564a9;  27 }  28 29 div#container fieldset  30 {  31  margin: 20px;  32  border: 1px solid #98b9d0;  33 }  34 35 ul#menu  36 {  37  list-style-type: none;  38  margin: 4px;  39  padding: 0px;  40 }  41 42 ul#menu li  43 {  44  float: left;  45  margin: 4px;  46 }  47 48 ul#menu li.active  49 {  50  background-color: #98b9d0;  51  border-left: 1px solid #3564a9;  52  border-top: 1px solid #3564a9;  53  border-bottom: 1px solid #e6eef6;  54  border-right: 1px solid #e6eef6;  55 }  56 57 ul#menu li a  58 {  59  text-decoration: none;  60  font-size: 10px;  61  padding: 2px;  62  color: #3564a9;  63 }  64 65 ul#files  66 {  67  list-style-type: none;  68  margin: 40px 0px 0px 0px;  69  padding: 0px;  70 }  71 72 ul#files li  73 {  74  background-color: #fff7c0;  75  border-bottom: 1px solid #efefef;  76  padding: 2px;  77  margin-bottom: 1px;  78 } 

What we should now have is illustrated in the following image.

Step 4 - Handling File Input Submissions with PHP

Let's start the PHP side of the tutorial by creating a Settings class. In this class we can save the upload password as well as the file path for the uploads folder.
We can then include the class into our page and use it's values when needed.
You can write PHP files with pretty much the same tools you use to write HTML and CSS, just remember to save the file with the .php suffix.

 1 2  

Without going any deeper into Object Oriented Programming (OOP), what the code does is it creates a new class with the kind of values that can be accessed without instantiating the class.
We can now access it's values simply by calling Settings::$password; and Settings::$uploadFolder; This is also the place where you can change the password whenever you please.
The <?php and ?> mark the beginning and the end of a PHP code segment. These segments can be written inside normal html pages and the server will interpret them when the page is requested.

Ok, now we get to business. In the html file we've been working with, let's add the following into the very top of the file. Yes, before the <head> tag.

 1 2 

First we tell the PHP interpreter to include our settings file. I've also set up a new variable $message. Later on I shall write process information into this variable and display it to the user.  1 2 //Has the user uploaded something?  3 if(isset($_FILES['file']))  4 { 

If the form has been submitted with a file, the $_FILE array should have a value with the key we used as the name of the file input field.  1 2 $target_path = Settings::$uploadFolder;  3 $target_path = $target_path . time() . '_' . basename($_FILES['file']['name']); 

Here we get the path to the upload folder we specified in the settings. On line 2, we add (concatenate) the name of the uploaded file into the target path.
Note also that I've added the current server timestamp into the beginning of the filename. There are two reasons for me doing this.
First it is used to store the date and second it will make sure that all files are of different names.
Should we be using a database behind this application, the time of adding would be there, and we could serialize the filenames and save the original name only in the database table,
but as there's no database, we can just use this workaround.

 1 2  //Check the password to verify legal upload  3  if($_POST['password'] != Settings::$password)  4  {  5  $message = "Invalid Password!";  6  }  7  else  8  {  If the submission was made without giving any password or if the given password was something other than the one defined in the settings, we won't handle the file and only return a message indicating a false password.  1 2  //Try to move the uploaded file into the designated folder  3  if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {  4 $message = "The file ". basename( $_FILES['file']['name']).  5  " has been uploaded";  6  } else{  7 $message = "There was an error uploading the file, please try again!";  8  }  9  }  10 } 

Ok, so the password was right, now what? Now we "save" the file. I say save in parenthesis since the file is actually already in the server; it's just in the temporary folder.
So to make the file accessible and to make sure the server won't delete it when the temp is cleared, we must move it to some safe location. I've used the move_uploaded_file function.
The function takes two arguments. First is the temporary name of the file assigned automatically by the server, and the other is the target path we assigned earlier.
The function returns a Boolean value indicating an successful operation. Again we set the message value to inform the user what happened.

 1 2 if(strlen($message) > 0)  3 {  4 $message = '

' . $message . ' ';  5 }  And that's how easy it is to upload files to server with PHP! Here I've just checked whether anything has been written into the message variable (length more that 0) and format it so we can style it with CSS. Step 5 - List the Uploaded Files  1 2 /** LIST UPLOADED FILES **/  3 $uploaded_files = "";  4 5 //Open directory for reading  6 $dh = opendir(Settings::$uploadFolder); 

The first thing to do is to create a folder handle. All it takes is one command. The variable uploaded_files is where we'll be writing the folder filenames in HTML format.

 1 2 //LOOP through the files  3 while (($file = readdir($dh)) !== false)  4 { 

Here we loop through the files in the folder. As long as we can read the next file in the folder into the file variable we do so and move on. Once we've gone through all the files, the function return false and ends the loop.

 1 2  if($file != '.' &&$file != '..')  3  { 

The '.' and '..' are also returned by this function so we'll have to make sure we don't attempt to do anything with those.

 1 2  $filename = Settings::$uploadFolder . $file;  3 $parts = explode("_", $file);  We add the name of the file into the path of the uploads folder and save it as filename variable. Then we explode the name of the file at the '_' character. This function returns an array of strings splitting the original string every time there's a '_'. Since there's one of those characters, we'll receive an array with the timestamp part as cell 1 and the original file name as cell 2.  1 2 $size = formatBytes(filesize($filename));  3 $added = date("m/d/Y", $parts[0]);  4 $origName = $parts[1];  Now that we have the timestamp value as it's own string, we can format it into a date and save the original filename as it's own variable. The filesize function provided by PHP returns the size of the file in bytes only, so we'll format it into a more readable form with the formatBytes function, which is covered in a bit.  1 2 $filetype = getFileType(substr($file, strlen($file) - 3));  3  $uploaded_files .= " •$origName $size -$added
• \n"; 

When uploading a file into the server, PHP provides us with the file type information, but since we have no place to store that information, we'll have to try to get the file type with a custom function.
I'm giving the three last chars of the file name as a parameter to the getFileType function (shown later on). I'm using the filetype variable to style the different files with CSS.
All that's left now is to generate an HTML string and add it into the uploaded_files variable and close the folder handle.

 1 2  }  3 }  4 closedir($dh);   1 2 if(strlen($uploaded_files) == 0)  3 {  4  $uploaded_files = " • No files found • ";  5 }  If no files were found, set the uploaded_files var to display a message. We also have to show the uploaded_files string somewhere; so add this line inside the <ul> with the id 'files'.  1 2   Step 6 - Auxiliary Function The getFileType function tries to guess what type the file is by reading the last chars of it's name. This won't work with extensions like .jpeg and .tiff. To make it more universal, we'd have to read a substring starting at the period and going to the end of the file name. But then if the name is something like my.new.car.pic we'd get new.car.pic as the extensions. So to make this really work we would have to find the last period in the name and take a substring from there on. But for the scope of this tutorial this is close enough.  1 2 function getFileType($extension)  3 {  4  $images = array('jpg', 'gif', 'png', 'bmp');  5 $docs = array('txt', 'rtf', 'doc');  6  $apps = array('zip', 'rar', 'exe');  7   8  if(in_array($extension, $images)) return "Images";  9  if(in_array($extension, $docs)) return "Documents";  10  if(in_array($extension, $apps)) return "Applications";  11  return "";  12 }  This next function formats the bytes into a more readable format. Just basic math -- nothing more. The function itself is from the PHP.net function comments.  1 2 function formatBytes($bytes, $precision = 2) {  3 $units = array('B', 'KB', 'MB', 'GB', 'TB');  4   5  $bytes = max($bytes, 0);  6  $pow = floor(($bytes ? log($bytes) : 0) / log(1024));  7 $pow = min($pow, count($units) - 1);  8   9  $bytes /= pow(1024,$pow);  10   11  return round($bytes,$precision) . ' ' . $units[$pow];  12 }  13 ?> 

And that's it for the PHP part. Just some more JS and CSS and we're all done.

Step 7 - A Touch of CSS for Increased Readability

What we have this far should look like:

But to make good use of the getFileType function and the class name it returns, I've added the next lines of CSS into the style.css file.

 1 2 ul#files li a  3 {  4  text-decoration: none;  5  color: #3564a9;  6  padding: 2px 25px;  7  background-position: left;  8  background-repeat: no-repeat;  9 }  10 11 ul#files li.Documents a  12 {  13  background-image: url('../images/text.jpg');  14 }  15 16 ul#files li.Images a  17 {  18  background-image: url('../images/picture.jpg');  19 }  20 21 ul#files li.Applications a  22 {  23  background-image: url('../images/zip.jpg');  24 }  25 26 p.error  27 {  28  background-color: #fff7c0;  29  border-bottom: 1px solid #efefef;  30  font-weight: bold;  31  color: #ff0000;  32  padding: 6px;  33 } 

I'm assigning an icon to each type of file. The icon's I've used are from the magnificent collection found at http://www.famfamfam.com.
Now what we should have is something like this.

Ah, much better.

Step 8 - Toggle File Visibility with jQuery

For a finishing bit, let's add some extra functionality with JavaScript. Create a new folder called "js" and in that folder make a new file, filestorage.js.
Then add the following line to end of the HTML page right before the </body> tag.

 1 2 

It's considered a good practice to include these kind of js files at the very end of the page to allow the Document Object Model (DOM) to load first.

 1 2 function HideFiles(selector)  3 {  4  //show all files  5  if(selector === "All files")  6  {  7  $("#files > li").show();  8  return true;  9  }  10  else  11  {  12  //show only the selected filetype  13 $("#files > li").hide();  14  $("#files > li." + selector).show();  15  return true;  16  }  17 }  The HideFiles function does two things. If the parameter selector is equal to 'All files', the function goes through all the <li> -items inside the files <ul> and makes them visible. If, however, some other parameter was given, the function hides everything and then shows only the ones with the same class name as the parameter.  1 2 function prepareMenu()  3 {  4 $("#menu li").click(  5  function () {  6  $("#menu li").each(  7  function(){  8 $(this).removeClass("active");  9  }  10  );  11  $(this).addClass("active");  12  HideFiles($(this).children().html());  13  return false;  14  });  15 16  //Select the first as default  17  $("#menu li:first").click();  18 }  The prepareMenu function adds a function to the onClick event on the menu <li>s. Upon a click, remove the class 'active' from all of them and then add it to the one that was clicked and call the HideFiles function with the text inside the element inside the clicked <li>. Finally, we invoke the onClick event on the first menu element to make sure it's selected as default when the page loads.  1 2 $(document).ready(function()  3 {  4  prepareMenu();  5 }); 

Don't forget to call the prepareMenu function when the page is loaded. This can be done easily by calling it inside the document's ready event as shown above.
Now the menu "buttons" should be working and upon clicking them the list of files should change.

Step 9 - Congratulate Yourself for a Job Well Done!

That's it! You should now have a working online file storage.
Just remember to create a "uploadFolder," and change its CHMOD to allow for modification. Instructions for this can be found all around the web and directly from your hosting provider.

This has been a tutorial for the beginners. Hopefully it was in depth enough without being TOO explanatory.