Creating a File Hosting Site with CodeIgniter

Creating a File Hosting Site with CodeIgniter

Mar 11th, 2009 in PHP by Henry Irish

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.

PG

Author: Henry Irish

This is a NETTUTS contributor who has published 1 tutorial(s) so far here. Their bio is coming soon!

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.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Andrew March 11th

    Whoa, refreshed the page and this article appeared!

    ( Reply )
  2. PG

    Keith March 11th

    Very nice. I would like to see more Code Igniter tuts.

    ( Reply )
  3. PG

    Michael March 11th

    Awesome, I’d love some more CI tutorials. I’ve been playing with it lately and really love it.

    ( Reply )
  4. PG

    insic March 11th

    quite usefull post. It would be more nice if you use SWF Uploader.

    And add a tip for uploading large files. :)

    and for the login form maybe it would be nice if you use the form_validation library so that you can encrypt the password easily.

    ( Reply )
    1. PG

      crysfel March 11th

      i agree, it is much better to do it with SWF Uploader.

      ( Reply )
      1. PG

        David Singer March 11th

        APC and a little JavaScript works even better :)

  5. PG

    Erwin Heiser March 11th

    Nice one and more CI please :)

    One tip though: would have been nice to see CI’s input class used e.g. $something = $this->input->post(’something’);
    You can even have it apply a Cross Site Scripting Hack prevention filter automatically for safer data input. http://tinyurl.com/9yrpnj

    As far as encrypting goes there’s a built-in class for that as well. Maybe future tuts can take into account the many useful classes and helpers CI provides.
    Other than that: top tut!

    ( Reply )
  6. PG

    Snorri - Css March 11th

    nice 1

    ( Reply )
  7. PG

    TheEarlOfPlums March 11th

    the codeigniter input class is there for a reason, use it!
    http://codeigniter.com/user_guide/libraries/input.html

    ie
    $username = $this->input->post(‘username’);
    instead of
    $username = $_POST['username'];

    ( Reply )
    1. PG

      Thorpe Obazee December 1st

      That doesn’t do anything unless you put on xss_clean in the config file.

      You can do
      $this->input->post('username', true);

      or just


      xss_clean($_POST);

      ( Reply )
  8. PG

    Devin Rajaram March 11th

    Very nice tutorial, I really loved it

    ( Reply )
  9. PG

    Sebastian March 11th

    You’ve missed some DB Fields in your Tutorial.
    Anyways…god tutorial! Great job!

    ( Reply )
  10. PG

    geminorum March 11th

    great!
    keep up with CI

    ( Reply )
  11. PG

    Carsten March 11th

    Nice tutorial. In your second picture you have a mistake. You need to change the headings (users/files).

    ( Reply )
  12. PG

    Jeff Adams March 11th

    WOW! That’s pretty much all I can say.

    i’m sure there are developers wondering about how this helps people but honestly, for folks like me who understand programming but don’t necessarily KNOW the way developers work, this is awesome.

    It actually ties in very nicely with the latest Diving into PHP tutorial over at Themeforest.

    Great – cheers for this!

    ( Reply )
  13. PG

    Drazen March 11th

    I would like more Video Tutorials, its boring me reading everything. I guess tutsplus.com is earning enought to pay for more video tutorials and pushing the quality of content.

    ( Reply )
  14. PG

    Peter C. March 11th

    A nice, if excessively brief, introduction to MVC concepts. Are there going to be any NETTUTS tutorials which don’t have a whole list of “problems” tagged on the end (or in comments)? Getting across ideas with sample code is nice, but not if there’s always a “do not use this in the wild” message.

    ( Reply )
    1. PG

      Meshach March 11th

      I agree.

      ( Reply )
    2. PG

      Marc March 14th

      But if they give a fully working “no strings attached” tutorial, there are alot of people who will just copy and paste and claim as their own

      ( Reply )
    3. PG

      Sam April 14th

      Damn straight Marc. Give someone half the chance, and they’ll scarper with it.

      And how is anyone to learn if you dont challenge them to progress with the code?

      ( Reply )
  15. PG

    Jorge Mudry March 11th

    Nice tutorial!! I hope to see more of these in the future =)

    ( Reply )
  16. PG

    yourboyvic March 11th

    @Drazen

    a lil’ graditude? maybe a lil’ less ‘I don’t like reading, it makes my head hurt!’

    ( Reply )
  17. PG

    Bruno Belotti March 11th

    I’m using Code Igniter just now : it’s powerful and really simple to learn.
    But some really good tutorials like this is always helpful!!

    Thanks a lot

    ( Reply )
  18. PG

    Gareth March 11th

    Nice, though you should have used $this->post->input() instead of $_POST

    ( Reply )
  19. PG

    Bobby March 11th

    Thanks for the Codeigniter tutorial!

    ( Reply )
  20. PG

    SmeX March 11th

    could someone write out the sql-code?

    ( Reply )
  21. PG

    Emil Nikov March 11th

    I am really glad to see a more advanced tutorial on CodeIgniter. Good work!

    ( Reply )
  22. PG

    Eduardo March 11th

    very cool ‘intermediate’ tutorial!
    The validation library is very cool, and it would be very nice if you had used it.’

    ( Reply )
    1. PG

      Henry Irish March 11th

      This tutorial was starting to get very long as it was: I didn’t want to have to go into even more detail (or people would have falled asleep before finishing it).

      Tutorials are to teach concepts, not to make a complete ( and final) site.

      ( Reply )
  23. PG

    saurabh shah March 11th

    nice tutorial and yes i agree with INSIC … n yes very helpful.. thnx for sharing…

    ( Reply )
  24. PG

    trs21219 March 11th

    Nice tutorial. I’m planning to submit a few screencasts on CI when i get some time. Some topics i might cover are building an advanced secure user/login system with permissions, building a shopping cart with paypal integration, and more. If you have any requests shoot me an email at

    trs21219 [at] gmail.com

    ( Reply )
  25. PG

    Matt H March 11th

    CI has a built in file uploading class as well. It takes a lot of the legwork out and has excellent error reporting.

    http://codeigniter.com/user_guide/libraries/file_uploading.html

    This tutorial is riddled with mistakes but it’s a good start! I like to see some CI tutorials going around.

    If you’re going to use CodeIgniter you might as well take advantage of it… (IE the comments about using the input class.

    I would change your login function to

    $query = $this->db->get_where(‘users’, array(‘username’=>$username, ‘password’=>$password), 1);

    if ($query->num_rows()>0)
    {
    $row = $query->row();
    return $row->id;
    }
    return false;

    ( Reply )
  26. PG

    Pachito Marco Calabrese March 11th

    i like it! I’d like to see more CI tuts!

    ( Reply )
  27. PG

    Mike March 11th

    Have a job coming up that will call for this!

    Would love to see more CI tuts too. Started out using CakePHP, but after working with ExpressionEngine I think I might give CI a go.

    ( Reply )
  28. PG

    Drazen March 11th

    @ yourboyvic

    These guys writing tutorials are getting payed 150 bugs!!! This tut is not more work than 3 hours, if even not less.

    For 50 $ / hour there have to be a video.

    I dont say this tutorial is bad but paying 150 $ for a text tutorial … i dont know.

    Maybe a lil more thinking instead of just writing ‘good, good’.

    ( Reply )
  29. PG

    Randy March 11th

    Nice job. CI tuts that explain a “real world usage” have been hard to find for me. Still trying to grasp the whole MVC thing, but this makes it easier.
    Thanks!

    ( Reply )
  30. PG

    Sergio maselis March 11th

    Thanks for the tutorial. I would love to see more CI tutorials please!!

    ( Reply )
  31. PG

    Cris McLaughlin March 11th

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

    $str = $this->db->insert_string(‘users’, $new_user);
    return $this->db->simple_query($str);
    }

    Its never a guarantee that an insert statement will work (MySQL server is down ect…). I agree with others suggestions that you could have elaborated more but overall a good tutorial. Keep it up!

    ( Reply )
  32. PG

    barat March 11th

    hmm … I may use it when I’ll start to learn Kohana … CI is “older” brother of Kohana … it still using PHP4 insteed of PHP5 … Kohana is evolution but … lot of nice ideas from CI can be used in Kohana as well :)

    ( Reply )
  33. PG

    Shane March 11th

    Very pleased to see an out-of-the-ordinary CodeIgniter tutorial.

    I love how clean the code looks compared to say, a typical WP theme that is a mess by comparison.

    ( Reply )
  34. PG

    mini March 11th

    Some comments:

    Like above I’d suggest using CI’s built-in libraries:
    - Input class
    - Validation class
    _ Uploading class

    If you use CodeIgniter you could / should adhere to the CI Style Guide:
    http://codeigniter.com/user_guide/general/styleguide.html
    Especially the use of short open tags is problematic since its use could be disabled on the server.

    There is already a full blown file hosting application online built with CI:
    http://xtrafile.com/xu2/home (Sources are available here: http://xtrafile.com/products/xtraupload-v2/ )

    ( Reply )
  35. PG

    markokaup March 11th

    Yey! Very nice article and please give us more Codeigniter tutorials!! =)

    ( Reply )
  36. PG

    Luke March 11th

    Very nice, although the 3rd point on having the script check for files already existing is not much of an issue, Ci automatically appends a number to the end of a file if it already exists.

    ( Reply )
  37. PG

    Chesham March 11th

    Nice to see a CI tutorial that actually shows you how to do stuff, I haven’t seen too many of them around. ;)

    ( Reply )
  38. PG

    Fabryz March 11th

    Tagging this :D

    Hope to see more CodeIgniter tuts in the future

    ( Reply )
  39. PG

    M.A.Yoosuf March 11th

    thank you an intro for me about CI

    ( Reply )
  40. PG

    M.A.Yoosuf March 11th

    please some Video Tuts pls on CI

    ( Reply )
  41. PG

    Ricardo March 12th

    Some ideas:

    1. Folder per user might be better.
    2. Create an MD5 Hash for the file and keep it handy, that number can also be used to create folders inside the user folder.
    3. If a file’s MD5 Hash is on the user’s list, let them compare both images and decide if they are the same or not. If MD5 Hash is the same but the image is not, then both files would be in the same folder, right? Different names would keep them separated.
    4. Keeping a file location table would also allow for some tasty RSS or XML! Yay!
    5. Same table could also keep tabs of which files go public or not. Even mark images that might be adult oriented. Put a link on the website so users report files, make the script note you when an adult image is uploaded (so you can quickly comply with local laws and regulations).
    6. In the users table or in the script, there should be a way so you could specify “Moderators” so you (or others you designate) could help you maintain your site running free (or almost free) of worries.
    7. There should also be a way to ban IPs… To keep away those you send away.
    8. Comments on public images would be kind of nice (or maybe even another table field so you know when the user expect comments on the image).

    For security? Nope, I can’t give advice, I still don’t know how to do it (yet, some day I’ll know, I’ll look into some suggestions posted here).

    ( Reply )
    1. PG

      Yoosuf March 12th

      that mean simply u re tring to make a solution for public access? anyway awsome ideas

      ( Reply )
  42. PG

    Prabhjeet Singh March 12th

    Great CI tut, and I always LOVE to read about CI. Please need more CI tuts.

    Thanks

    ( Reply )
  43. PG

    Cristhian Bedon March 12th

    Great tut nice steps by steps.

    ( Reply )
  44. PG

    Vasili March 12th

    Really nice tutorial. ;) I loved the design for the demo, do you mind telling me the code used to style the file input field?

    ( Reply )
  45. PG

    Chris Gunther March 12th

    Nice to see a CI tutorial on here. Looking forward to more.

    ( Reply )
  46. PG

    sivaji March 13th

    I think the author was confused with the table names

    users table suppose to have id, username and password and the files table suppose to have id, owner and name. isnt it ?

    ( Reply )
  47. PG

    Eric March 13th

    Nice tutorial!

    ( Reply )
  48. PG

    Jash Sayani March 14th

    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.

    ( Reply )
  49. PG

    Dean March 15th

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

    ( Reply )
    1. PG

      Rob March 24th

      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!

      ( Reply )
  50. PG

    Lima March 16th

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

    ( Reply )
    1. PG

      Dean March 16th

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

      ( Reply )
  51. PG

    Robert Barnett March 16th

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

    ( Reply )
  52. PG

    Lawrence March 19th

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

    ( Reply )
  53. PG

    Anarky March 26th

    it’s useful, tnks

    ( Reply )
  54. PG

    jay March 26th

    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.

    ( Reply )
  55. PG

    Jozan March 31st

    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`)
    );

    ( Reply )
  56. PG

    Mehdi April 15th

    Nice Tut !
    Keep up the CI !

    ( Reply )
  57. PG

    Raymond Selda April 16th

    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!

    ( Reply )
  58. PG

    Jay April 20th

    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

    ( Reply )
  59. PG

    HJ May 30th

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

    ( Reply )
  60. PG

    fet June 1st

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

    ( Reply )
  61. PG

    ivanargulo June 5th

    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);

    ( Reply )
    1. PG

      Vincent June 22nd

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

      ( Reply )
    2. PG

      tes December 24th

      it makes
      “Internal Server Error

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

      on me

      ( Reply )
  62. PG

    trev June 19th

    I thought it was confusing to follow.

    ( Reply )
  63. PG

    Black rider June 29th

    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.

    ( Reply )
  64. PG

    Joey July 11th

    Error Number: 1062

    Duplicate entry ‘0′ for key 1

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

    ( Reply )
  65. PG

    Joey July 11th

    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.

    ( Reply )
    1. PG

      Mauro July 30th

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

      ( Reply )
  66. PG

    Nadeya Rumman July 28th

    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`)
    );

    ( Reply )
  67. PG

    Torsti August 1st

    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?

    ( Reply )
  68. PG

    otto1303 August 2nd

    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.

    ( Reply )
    1. PG

      otto1303 August 2nd

      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`)
      );

      ( Reply )
  69. PG

    Jaspal Singh August 2nd

    Nice tutorial using CodeIgniter.
    Thanks for sharing.

    ( Reply )
  70. PG

    vinz September 18th

    i liked this thing,
    helped a lot

    ( Reply )
  71. PG

    Ashutosh October 20th

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

    ( Reply )
  72. PG

    Steven October 24th

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

    ( Reply )
  73. PG

    amarshukla123 October 30th

    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

    ( Reply )
  74. PG

    Gie November 13th

    Hmm…. very nice tutorial… thanks friend

    ( Reply )
  75. PG

    Purag November 24th

    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”?

    ( Reply )
  76. PG

    Wouter Vervloet November 28th

    @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.

    ( Reply )
  77. PG

    Purag November 30th

    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?

    ( Reply )
  78. PG

    idwebsolutions December 17th

    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’);

    ( Reply )
  79. PG

    Omar January 7th

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

    ( Reply )
  80. PG

    Jesse January 11th

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

    ( Reply )
  81. PG

    boris badenov February 1st

    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

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    February 1st