# Creating a File Hosting Site with CodeIgniter

I have seen a few introductory tutorials for Codeigniter, and was hoping to show you something a little more advanced. This tutorial will show you how to build a powerful web application for hosting images, using the flexibility of Codeigniter. This tutorial should teach you about the MVC coding philosophy, integral to producing serviceable applications.

### Step 1: Setup

Before we go anywhere near the code, we need to do some setup. Fire up your favorite database editor (I'll be using SQLBuddy) and create a new database called 'uploadr'. Inside this, create two tables: 'users' and 'files'. Set up users to have a primary-key, auto-numbered 'id' column, along with two varchar columns: 'password' and 'username'. The files table needs another 'id' column (again primary-key and auto-numbered), as well as an integer 'owner' column, and a varchar 'name' column.

Since this tutorial is focussed on learning Codeigniter programming and about MVC, we are going to forgo all of the styling stuff (like CSS, photoshop). To this end, I've created a custom Codeigniter install for you, with all the files created, and the views (mostly) HTML-d and CSS-d. The two things you'll need to change are the config and database settings. I even included a "Beta" stamp, so it'd feel even more like a web-startup!

Now onto the first bit of meat! Open up the 'login.php' controller and create a function called 'register'. This is going to control the entire registration process. First, we need to check whether any POST requests have been sent to the server. In this case, these will signify someone trying to register. We can do this by checking whether $_POST['username'] is set. If it is, then we know someone has tried to register, and can enter it into the DB. If the user has yet to try registering, it detects this and automatically sends them to the 'register' view that I've coded for you. You'll notice the line: This is calling the function 'register' in the model 'users'. At the moment this will not work, since we haven't loaded the model. We do this in the same way as loading views, but since we are going to be using this model extensively throughout this class, we will load it in the constructor function (the function with the same name as the class), so that it is always loaded and available: You're probably interested in what the registration function actually contains. Well, it simply uses a couple of Codeigniter's active record functions, which allow for DB manipulation. The big advantage of using Codeigniter's built in active record functions (besides the fact that they're nice and simple) is that they're database agnostic: you can easily switch in and out different database types (for example mySQL, SQLite) in the DB config file without affecting the application. In the case of our registration, we're adding an entry to the users table. Create this function in the 'users.php' model: The only thing worth noticing in the registration view are the site_url() and base_url() functions. These respectively give your site's URL with and without the index.php/ suffix. The greatest advantage to them is that you can change your site's URL structure without having to go through all the links: it just takes one change in your config file. Once this is all setup, we can try registering an account. The function in our controller should redirect us to the login page again after our account is created. ### Step 3: Login Now that we have a few users set up, we need a way of actually letting them into the site. For this, we are going to use Codeigniter's sessions class. Although this actually uses cookies, it works in a very similar way to normal PHP sessions, just with more options (I recommend you check the userguide). To start with, we need to create the function that the login button currently points to, 'go'. This function will need to collect the information that the form has submitted, and then check it against the DB using a model. If all is correct, it'll start a session, and redirect the user to their files. If they mistyped their information, they'll be redirected to the login page. Parts of this function should look very familiar to you from the register function: it collects$username and $password, before submitting them to a model (this time 'login'). After this however, the differences begin to occur. It then checks to see if the login has failed; if it has, then the user is redirected back to the login page. However, if the login is successful then the script creates a session, setting 'userid' to the users id. All that we need now for the login script to work is the model. Add this function to the 'users' model we used earlier: A quick rundown: first, it queries the database looking for any users with exactly the same username and password. If it doesn't find any, then the number of rows will be 0, and the function returns false. If somebody was found, then it uses another of Codeigniter's active record functions to load it as an object. This objects comes as an array of DB rows, each containing an object with that rows information. Since we want the first and only row, we take it out of$result, and then return the id from it.

We will need to check whether the user is logged in whilst on the profile page. To do this, we simply insert two lines of code into the constructor of the profile controller. This will check that the session contains a userid. If it doesn't, then redirect to the login page. If it does, then all is fine, and it gets turned into a public variable. Whilst we're changing the constructor, we will load the two models that we will need for the profile page:

The final thing we need to do is make it possible to logout. This is achieved by simply setting the userid to nothing, deleting it. All it requires is one simple function:

Right then, we've just logged in for the first time. What are we greeted with?

Not bad, not bad, although that 'sample file' isn't being generated from our database, it's static. We'll rectify that soon, but first we need to change the permissions of the 'file' folder so that Codeigniter can read and write on it. I changed it to 777 Permissions:

Now that that's out of the way, let's get back to some coding! We need to load all the users files out of the database, and to do that we're going to need...

... a model! This time however, we're going to create it in the 'files.php' model, so we keep our user table and file table separate. Insert this function:

This again draws from earlier sections of this tutorial, so you should be able to understand it. Basically, it gets all the rows where the owner = the user's id, and returns them in a nice array of objects. Let's create something in the 'profiles' controller to interface with it, and to pass the info onto the view. Amend the index function with this:

Again, a very simple function. It takes the results passed to it from the files model, and packages them to the view. Codeigniter passes data to the view usually through an array (in this case data). It will then automatically explode the array into lots of variables, so when we go to the view, it will be able to access the database results through $file, rather than$data['file']. Let's put this lovely database result into the view! Stick this into 'profile.php', replacing the code that the HTML comment tells you to.

The foreach loop loads each row of the array in turn, and makes it accessible via the $file object. We then, using the sample "section" as a template, fill in all the links and the name with information for the new$file object. We will how the delete function works later, and how the view link works after we've uploaded something.

If you open this in your browser now, you won't see anything. This is because we haven't got any files uploaded! Well, we need to rectify that, so we'll need to make an uploading form. Let's do the controller first; open 'profile.php' and add this function:

This function adds quite a few new things: especially Codeigniter's file handling. It starts off fairly simply, checking to see whether a form has been submitted by looking for a file. If the file doesn't exist, it simply shows the upload view (which we'll be updating next). If the file does exist, then it extracts reads the temporary file that the server has generated. The directory of the temporary file can be found at $_FILES['your_file']['tmp_name'], and the file can be read from this directory by Codeigniter's read_file. This loads all of the files information into the$file variable.

The next line gets the file's name from the global $_FILES in a similar way to getting the temporary directory. Armed with these two pieces of information, codeigniter writes the file to the files folder in the same directory as it's index file. Lastly, the file needs to be added to the database. Again, we're going this with a model, this time the 'add' function in 'files'. We'll see how that works in a minutes, but we now need to create the uploading form in the view. Add this where the 'upload.php's HTML comment tells you to: Replace the current HTML with this. The important thing to note here is that when we're uploading files, we use an input type=file, which allows us to pick a file to upload. Also, we have to specify an enctype in our form tag, so that the server knows that it's recieving a file and to save it. Not too interesting to us back-end coders, but still crucial! Let's have a quick look at what we've created: Now we move onto the final bit of the file uploading script, the model. This adds the file to the database, with it's name and owner, so the server knows which files belong to whom. Let's take a look; add this to your 'files' model: Again leveraging Codeigniter's active record functionality, we add a row to the database with the name of the file and the owner. We get the owner by finding the users id from the session data that we saved earlier when logging on. All in all, a very simple function. Let's trying uploading a nice photo, eh? Et, Voila! Looking into the 'files' folder, we see that the file that we uploaded has appeared there, as if by magic (Codeigniter magic!), and we see why the view link works, since it simply points directly to the file in the directory. With this done, all that remains for this tutorial is deleting files. ### Step 5: Deleting Files Ok, the last bit. This shouldn't take so long, since you'll be able to utilize the ideas that you learnt earlier to understand this. First we'll add this code to our 'profiles' controller: And this code to our 'files' model: The first controller should be very easy to understand. It calls the delete function from the files model (which we defined at the same time), which generates the name of the file. It then uses a basic PHP function to delete the file with that name in the files directory. Finally, it sends back to the users profile (which is now minus one file). The model is slightly more complex. It needs to return the name of the file as well as deleting it, so first it queries the database to get the files details. It loads this into the$result variable, and then goes on to delete the file. It then returns the 'name' column of the first row of the array (the only row that the query returned), which is then used in the above controller.

Let's try to delete a function:

And click delete...

Hooray! It worked. I guess we're all done then!

### Final Thoughts

Delete Files

Of course, this code should not be run on a server without some serious improvements. Here are a few major problems with it:

• The passwords are all unencrypted. This means that if anyone should break into your database, they will be able to steal all of your users data with minimal effort. As I'm sure you'll all agree: not good. This could easily be solved by adding some simple hashing to the passwords.
• The files are not private. A user may want to ensure that the files they upload are only visible by them, and not by someone who just guesses a bunch of urls. This would probably require another controller for serving the files (which checks for session data).
• The script does not check that files exist before writing files. This could cause conflicts with your files, or it could result in file data being overwritten. Whichever: not good. This could be solved with a simple DB check to ensure that the file has not been taken, and could be minimized by giving users their own directories within the files folder.
• No errors are being generated. This doesn't exactly help the user find out what they're doing wrong, and although this isn't (too) much of a problem on such a small site with such limited actions, it still could be improved.

All in all, you've created quite a powerful little web application, especially due to the small amount of code that you had to write. Due to Codeigniter's nature, it's quite easily extended, both to resolve the above problems, and to add new features, like renaming files. I also hope that this tutorial taught you a bit about using MVC concepts, and the power that they bring: by simply adjusted the models on our application, we can swap our the DB for text files, XML or anything, and by changing the views, we can completely re-theme without breaking functionality. Amazing!

• Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.