Hosting Scripts (depraced!) > Uploadr

Uploadr


Date: 10 July 2010 | Posted by: SpiritStorm
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.
view plaincopy to clipboardprint?

1. function register()
2. {
3. if(isset($_POST['username'])){
4.
5. // User has tried registering, insert them into database.
6.
7. $username = $_POST['username'];
8. $password = $_POST['password'];
9.
10. $this->users->register($username, $password);
11.
12. redirect('login');
13.
14. }
15. else{
16. //User has not tried registering, bring up registration information.
17. $this->load->view('register');
18. }
19. }

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:
view plaincopy to clipboardprint?

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

$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:
view plaincopy to clipboardprint?

1. function Login()
2. {
3. parent::Controller();
4. $this->load->model('users');
5. }

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:
view plaincopy to clipboardprint?

1. function register($username, $password)
2. {
3. $new_user = array (
4. 'username'=>$username,
5. 'password'=>$password
6. );
7.
8. $this->db->insert('users', $new_user);
9.
10. return true;
11. }

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.
view plaincopy to clipboardprint?

1. function go()
2. {
3.
4. $username = $_POST['username'];
5. $password = $_POST['password'];
6.
7. //Returns userid if successful, false if unsuccessful
8. $results = $this->users->login($username,$password);
9.
10. if ($results==false) redirect('login');
11. else
12. {
13. $this->session->set_userdata(array('userid'=>$results));
14. redirect('profile');
15. }
16.
17. }

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:
view plaincopy to clipboardprint?

1. function login($username, $password)
2. {
3.
4. $query = $this->db->get_where('users', array('username'=>$username, 'password'=>$password));
5.
6. if ($query->num_rows()==0) return false;
7. else{
8. $result = $query->result();
9. $first_row = $result[0];
10. $userid = $first_row->id;
11.
12. return $userid;
13. }
14.
15. }

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:
view plaincopy to clipboardprint?

1. function Profile()
2. {
3. parent::Controller();
4.
5. $this->load->model('users');
6. $this->load->model('files');
7.
8. $this->userid = $this->session->userdata('userid');
9. if (!isset($this->userid) or $this->userid=='') redirect('login');
10. }

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:
view plaincopy to clipboardprint?

1. function logout()
2. {
3. $this->session->set_userdata(array('userid'=>''));
4. redirect('login');
5. }

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:
view plaincopy to clipboardprint?

1. function get($userid)
2. {
3. $query = $this->db->get_where('files', array('owner'=>$userid));
4. return $query->result();
5. }

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:
See full article