Creating a File Hosting Site with CodeIgniter

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!

Step 2: Registration

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.

	
function register()
{
	if(isset($_POST['username'])){
		
		// User has tried registering, insert them into database.
		
		$username = $_POST['username'];
		$password = $_POST['password'];
		
		$this->users->register($username, $password);
		
		redirect('login');
		
	}
	else{
		//User has not tried registering, bring up registration information.
		$this->load->view('register');
	}
}

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->users->register($username,$password);

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:

function Login()
{
	parent::Controller();
	$this->load->model('users');
}	

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:

function register($username, $password)
{
    $new_user = array (
    	'username'=>$username,
    	'password'=>$password
    );

    $this->db->insert('users', $new_user);

	return true;
}

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.

function go()
{

	$username = $_POST['username'];
	$password = $_POST['password'];

	//Returns userid if successful, false if unsuccessful
	$results = $this->users->login($username,$password);
	
	if ($results==false) redirect('login');
	else 
	{	
		$this->session->set_userdata(array('userid'=>$results));
		redirect('profile');
	}

}

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:

function login($username, $password)
{

	$query = $this->db->get_where('users', array('username'=>$username, 'password'=>$password));
	
	if ($query->num_rows()==0) return false;
	else{
		$result = $query->result();
		$first_row = $result[0];
		$userid = $first_row->id;
		
		return $userid;
	}
	
}

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:

function Profile()
{
	parent::Controller();
	
	$this->load->model('users');	
	$this->load->model('files');

	$this->userid = $this->session->userdata('userid');
	if (!isset($this->userid) or $this->userid=='') redirect('login');
}

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:

function logout()
{
	$this->session->set_userdata(array('userid'=>''));
	redirect('login');
}

Step 4: Viewing and Uploading Files

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:

function get($userid)
{
    $query = $this->db->get_where('files', array('owner'=>$userid));
    return $query->result();
}

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:

function index()
{
	$data['files'] = $this->files->get($this->userid);
	$this->load->view('profile', $data);
}

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.

<?php foreach($files as $file): ?>

<div class="section">
	<span><?=$file->name?></span>
	<div style="float: right;">
		<span><a href="<?=base_url()?>files/<?=$file->name?>">View</a></span>
		<span><a href="<?=site_url("profile/delete/".$file->id)?>">Delete</a></span>
	</div>	
</div>

<?php endforeach; ?>	

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:

function upload()
{
	if(isset($_FILES['file'])){
		$file 	= read_file($_FILES['file']['tmp_name']);
		$name 	= basename($_FILES['file']['name']);
		
		write_file('files/'.$name, $file);

		$this->files->add($name);
		redirect('profile');		
	}

	else $this->load->view('upload');
}

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:

<form enctype="multipart/form-data" action="<?=site_url('profile/upload')?>" method="post">

	<div id="boxtop"></div><div id="boxmid">

		<div class="section">
			<span>File:</span>
			<input type="file" name="file" />
		</div>

	</div><div id="boxbot"></div>

	<div class="text" style="float: left;"><p>Before uploading, check out</p><p>the <a href=#>Terms of Service</a>.</p></div>
   	<div class="text" style="float: right;">

	<input type="submit" value="Upload" name="upload" class="submit" />
</div>
<br style="clear:both; height: 0px;" />

</form>	

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:

function add($file)
{
    $this->db->insert('files', array('owner'=>$this->session->userdata('userid'),'name'=>$file ));
}

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:

function delete($id)
{
	//This deletes the file from the database, before returning the name of the file.
	$name = $this->files->delete($id);
	unlink('files/'.$name);
	redirect('profile');
}

And this code to our ‘files’ model:

function delete($fileid)
{
	$query = $this->db->get_where('files',array('id'=>$fileid));
	$result = $query->result();
	$query = $this->db->delete('files', array('id'=>$fileid));
	return $result[0]->name;
}

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.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.ericdgreene.com Eric

    Nice tutorial!

  • http://www.jashsayani.com Jash Sayani

    Wow! Amazing work. I am currently using another CodeIgniter script on my Hosting site, but am tempted to move to yours….

    However, it would be great to see ability to create Paid accounts and set upload/download size limits, etc.

  • http://deanperry.net Dean

    Great tut! I would also like to see more CodeIgniter tutorials as I’ve just started using it.

  • found a ripper
    • Rob

      This is a totally disgraceful and shameless rip!

      People like this need stringing up by the privates! People who rip content p*ss me off!

  • Lima

    Is there any demo of above tutorial? Don’t know why but i can’t get this to work!

    • http://deanperry.net Dean

      Same here :(
      If only there was a SQL database backup that we could import into MySQL.

  • Robert Barnett

    Fyi, the step one image and setup paragraph are incongruent, the image is wrong according to the instructions.

  • http://www.bubble-bytes.com/ Lawrence

    Great Tut. Would be nice if someone could add the whole source with some SQL!

  • Anarky

    it’s useful, tnks

  • jay

    nice forum, post more codes.
    very nice, great help for us studying and practicing code igniter
    email me something new and more powerful codes in code igniter.

  • http://dajozan.net Jozan

    Great tut again! Thanks!

    But… In the first pic, you can see a little mistake. That’s why the example code doesn’t work very well.

    Some people asked the SQL code, there it’s!

    For users table:
    CREATE TABLE `users` (
    `id` int(11) NOT NULL auto_increment,
    `username` varchar(255) NOT NULL,
    `password` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
    );

    And for files table:
    CREATE TABLE `files` (
    `id` int(11) NOT NULL auto_increment,
    `owner` int(11) NOT NULL,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
    );

  • Mehdi

    Nice Tut !
    Keep up the CI !

  • http://www.raymondselda.com/ Raymond Selda

    I was using CI’s Upload class but unfortunately I can’t get around it. This tutorial really helped me a lot especially the way you approached file uploads. Looking forward to many more of your CI tutorials. Thank you very much!

  • Jay

    Just for beginner’s to know, this IS a very basic introduction

    More advanced programmer’s would realise the db maintenance and file maintenance issues with this code and it’s lack of security.

    Getting this system more secure and robust would take a lot of extra work and probably add a 4x or more bulk to the code (ie, deleting users, user/file checks, preventing file collisions ie overwrites, encrypting password (md5 should suffice or sha1, along with blowfish for getting password back aswell))) etc etc

    so to the beginner’s take this guide with a pinch of salt. It’s excellent to get u into codeigniter but wouldn’t stand up in real world application

  • HJ

    Like it, but I’m missing the maps-function. So i rebuilded it a bit, now you can add and delete maps too ;) Thanks!

  • fet

    anyhow im wondering on what kinda of hosting service can i host this stuff , do i need a dedicated one or a normal one

  • http://ivanargulo.wordpress.com ivanargulo

    It’s enough with a dedicated server. One of the most powerful features in CodeIgniter is its able to work in a wide range of servers.

    If you want to restrict the access to your files with the browser, you could use a .htaccess file, and to load the files using a controler, like this:

    $this->load->helper(‘download’);
    $data = file_get_contents($path_to_document);

    $file_name = split(‘/’, $path_to_document);
    $size = sizeof($file_name);
    $name = ‘dl_’ . url_title($name[$size - 1]);

    force_download($name, $data);

    • Vincent

      A normal shared virtual server will do. An entire dedicated server just to run these type of scripts is a bit over the top :)

    • tes

      it makes
      “Internal Server Error

      The server encountered an internal error or misconfiguration and was unable to complete your request. ”

      on me

  • trev

    I thought it was confusing to follow.

  • Black rider

    Can you please help…
    I have set-up everything and now I am moving to a new server but this system has a phpMYADMIN.

    I tried to set it up but I get a error saying it can’t link to the database…
    Can you please help.

  • http://www.joeyfigaro.com Joey

    Error Number: 1062

    Duplicate entry ’0′ for key 1

    INSERT INTO `users` (`username`, `password`) VALUES (‘******’, ‘***********’)

  • http://www.joeyfigaro.com Joey

    It may be an error on my part… and most likely is. I have little experience with working out SQL bugs. I’m guessing that key ’1′ is ‘id’ …? There aren’t any entries inside of that field.

    • Mauro

      Looks like you forgot to set the auto_increment attribute of the field ‘id’…

  • Nadeya Rumman

    very nice & helpfull.

    But… In the first pic, you can see a little mistake. That’s why the example code doesn’t work very well.

    Some people asked the SQL code, there it’s!

    For users table:
    CREATE TABLE `users` (
    `id` int(11) NOT NULL auto_increment,
    `username` varchar(255) NOT NULL,
    `password` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
    );

    And for files table:
    CREATE TABLE `files` (
    `id` int(11) NOT NULL auto_increment,
    `owner` int(11) NOT NULL,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
    );

  • http://www.tuokio.org Torsti

    I fail… :/ I don’t understand how I register for my Uploadr? Where I put my password and username? Now I’m only made databases and tables. Can someone help me?

  • otto1303

    Hi, there are many great tutorials in this site.

    I get this message: “A Database Error Occurred
    Unable to connect to your database server using the provided settings.”

    Where I put my database settings?, please.

    • otto1303

      It’s OK, I found it, and chage my users table by

      CREATE TABLE `users` (
      `id` int(11) NOT NULL auto_increment,
      `username` varchar(255) NOT NULL,
      `password` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
      );

  • http://www.jsxtech.com Jaspal Singh

    Nice tutorial using CodeIgniter.
    Thanks for sharing.

  • http://satzee.co.cc vinz

    i liked this thing,
    helped a lot

  • http://sancharwireless.in/ Ashutosh

    can anyone help in captcha.
    I wanted to include a captcha protection

  • Steven

    Is there a way to show all the files that were uploaded to the server? In a nicely looking way??

  • amarshukla123

    In the beginning of this tutorial,the image showing tables is incorrect by mistake.Users table is showing fields id,owner,name which should be id,username,password and accordingly to the files table.
    Correct me if I am wrong…

    When I tried to run the project and clicked on login button I get the following error saying -

    Forbidden

    You don’t have permission to access /uploadr-Final/< on this server.

    AND my url gets liek this –
    http://localhost/uploadr-Final/%3C?username=Username&password=Password&login=Login

  • http://gie-art.com Gie

    Hmm…. very nice tutorial… thanks friend

  • Pingback: Links για Code Igniter Tutorials | Newsfilter

  • Purag

    I’m using a free host where I’m not given the privilege of a customized database title — it has a randomly generated prefix and an underscored. Everything after the underscore I can customize.

    In the script, the database has to be called “uploadr.” In my case, it would be “a73982784_uploadr,” to give a random example.

    Where do I go to change the database identification in the script itself to “a73982784_uploadr” instead of “uploadr”?

    • gg

      i wanna know too!!

  • http://www.baseworks.nl Wouter Vervloet

    @Purag: In the database.php config file you can set your database name. That should do the trick.

    Nice tut… It’s a good place to start and in the spirit of CI itself: it’s easy to extend your basic classes.

  • Purag

    Thanks a bunch, Wouter. :)

    Now, another question: I tried registering with the Username and Password field empty, and the script registered me. I’m able to log in with the username “” and the password “”. This also works for uploading files — you can not choose a file and click upload and have it be a blank file.

    My question is, how can I make it so that it gives them a javascript alert if the fields are empty?

  • idwebsolutions

    for security, please change ur code to :

    function register()
    {
    if(isset($_POST['username'])){

    $username = $_POST['username'];
    $password = sha1(‘password’);

    function go()
    {

    $username = $_POST['username'];
    $password = sha1(‘password’);

  • http://mayavps.com Omar

    Slowly getting intimate with CodeIgniter. It really is powerful, especially for such little code!

  • http://www.jream.com Jesse

    This is a fantastic tutorial! I am trying to learn CI and this is helping me get off the slow paced part. Awesome!

  • boris badenov

    Awesome tutorial but if this is for the beginner (was this not declared?) Oh, maybe assumed and we all know what happens then.I just spent hours because I did not know enough to autoload the session library

  • Pingback: CodeIgniter Tutorials to Help You Get Started | KomunitasWeb

  • Purag

    For organization purposes, I’ve attempted to make the script make a new directory (after user registration) under the name the user registered with. It just doesn’t seem to be working. This is the code I have, if anybody could fix it:

    function register()
    {
    if(isset($_POST['username'])){

    // User has tried registering, insert them into database.

    $username = $_POST['username'];
    $password = $_POST['password'];

    mkdir(‘/public_html/files/’.$username, 0755);

    if(isset($_FILES['file'])){
    $file = read_file($_FILES['file']['tmp_name']);
    $name = basename($_FILES['file']['name']);

    write_file(‘files/’.$username, $file); // REMEMBER to write the file AFTER the directory is created.

    $this->files->add($name);
    redirect(‘profile’);
    }

    $this->users->register($username, $password);

    redirect(‘login’);

    }
    else{
    //User has not tried registering, bring up registration information.
    $this->load->view(‘register’);
    }
    }

    Thanks!

    • Purag

      I just realized that I”ll also need to edit the delete function. Could somebody help me with this?

  • Pingback: Getting Started with CodeIgniter and How to Create All Those Great Apps | DevSnippets

  • Pingback: DevSnippets.com: Getting Started with CodeIgniter and How to Create All Those Great Apps | Webs Developer

  • Arjun

    In Step 3, where ou add all the code he’s given you?

  • Pingback: Getting Started with CodeIgniter and How to Create All Those Great Apps « Web Development News

  • Natasha

    Please help. I’m just starting with CodeIgniter.
    I’ve copied all files to the directory uploadr, created tables in the database. How can I run this?
    when I enter http://localhost/uploadr into browser I get file not found error. When I enter http://localhost/uploadr/login I get broken link error.

  • http://iH8sn0w.com XxTheUnknownxX

    @Natasha Try to make sure you are typing the EXACT URL in your browser, a file not found is when you entered the wrong url.

  • Pingback: Getting Started with CodeIgniter and How to Create All Those Great Apps | PHP Lovers

  • Martin

    @natasha, you have to enable mod_rewrite in apache web server.

  • http://mskhirwar.wordpress.com Man Mohan

    Great tutorial,

    It assist me in understanding session class with codeigniter.

    Awaiting for your upcoming tuts.

    Thanks buddy…….

  • http://webotle.com Alex Stomp

    huh.. not a new tut, but I’d forgotten about it.. Will definitely set something like this up for my group.. file-sharing is always handy :D

  • http://cihip.com chip

    Creating a File Hosting Site with CodeIgniter for thanx.