Php login system for multiple users

Seems like I’m in blogging mode for the past few days. This time I’m going to talk about how to make a login system in php. Wait, if you still remember I have made one before but using only sessions. And its not actually designed to handle multiple users. Since the logout script just destroys the whole session. Which means that other users who are actually currently logged in will also be logged out. And that’s not really good.

What we will be doing today is a login system which can handle multiple users. And we will also be implementing object oriented programming. To make things more organized in clean.

 

Building the table

First, you have to create a database. Then just paste these sql statements below. You can use phpmyadmin to do the job. Just go to the sql tab, and paste it in the box that will appear. Then click on go.

CREATE TABLE IF NOT EXISTS `users` ( `User_ID` int(11) NOT NULL AUTO_INCREMENT, `Username` varchar(20) NOT NULL, `Password` varchar(35) NOT NULL, `Registered_IP` varchar(15) NOT NULL, `Email` varchar(30) NOT NULL, `Registration_Date` datetime NOT NULL, `Last_Login` datetime NOT NULL, `User_Class` int(11) NOT NULL, `Active` int(11) NOT NULL, PRIMARY KEY (`User_ID`), UNIQUE KEY `Username` (`Username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

 

 

 

User class

Let’s create a class where we will put all the functions and variables which can be associated with the user. The codes below maybe a little bit unfamiliar since we will not be using the usual way of connecting to the mysql database. This time we will use ez sql, a framework which can manipulate different kinds of database. You can use the links below to learn about ez sql:

http://www.catswhocode.com/blog/php-fast-and-easy-sql-queries-using-ezsql

http://jvmultimedia.com/docs/ezsql/ez_sql_help.htm

First, you have to import the ez sql core files into the user class. Then create an object:

require_once('ez_sqlsharedez_sql_core.php');
require_once('ez_sqlmysqlez_sql_mysql.php');

$mdb = new ezSQL_mysql('root', '', 'login_system', 'localhost');

Then declare the variables, this should match the ones that are on the table that we created earlier:

class users{

private $user_id;
private $username;
private $password;
private $reg_ip;
private $email;
private $reg_date;
private $last_login;

}

Next, create a function that will check if the user is registered or not. This function will be called every time a user will login.

function check_user($uname, $pword, $ip){ global $mdb; $exist = $mdb->query("SELECT Username, Password, Registered_IP FROM users
WHERE Username='$uname' AND Password='$pword' AND Registered_IP='$ip'"); return $exist; }

This function takes up 3 arguments. The username, the password, and the ip address of the computer from where the page is being accessed. It then queries the database if it finds a match for all those data. And returns true if it finds it. If it finds a record which matches the username, password, and ip. Then the function returns 1. If not, it returns 0.

Next, create a function that will set the last login date for the user:

function set_last_login($uname){
	global $mdb;
	$mdb->query("UPDATE users SET Last_Login=NOW() WHERE Username='$uname'");
}

NOW(), is a mysql function which returns a datetime stamp. Like this one:

2011-05-12 20:01:07

After that, we set the user as active:

function set_active($uname){
	global $mdb;
	$mdb->query("UPDATE users SET Active=1 WHERE Username='$uname'");
}

Sessions and cookies can’t be shared between browsers and computers that’s why we need to do this. Setting the active field into 1 means the user has already been logged in.
Then we create another function which will be called upon user logout. This will switch the active value to 0 for the corresponding user:

function set_inactive($uname){
	global $mdb;
	$mdb->query("UPDATE users SET Active=0 WHERE Username='$uname'");
}

Then we create another function which will check if the user is  logged in or not. This will ensure that the user is logged in only one place. A sort of security feature.

function check_active($uname){
	global $mdb;
	$active = $mdb->query("SELECT Username, Active FROM users WHERE Username='$uname' AND Active=1");
	return $active;
}

 

Session class

Next, lets create a session class. This will contain all the functions related to manipulating the session array.

class sessions{

function create_session($username, $ip){
	$_SESSION['log_users'][] = array('username'=>$username, 'ip'=>$ip);

}


}

Okay, so what we just did is to declare a new session. Then assigned an array into it, which contains the username and the ip address.
Next, we create another function which checks the session if it contains the username and the ip address of the current user. It loops through the session array and if it finds a record which matches the username and ip, it returns 1.

function check_session($username, $ip){
	
	foreach($_SESSION['log_users'] as $lu){
	
		if(($lu['username']==$username)&&($lu['ip']==$ip)){
			return 1;
		}
	}
}

Lastly, we create a function which logs the user out of the system. This one also loops through the session array, similar to the check_session() function. But this time, when it finds the username which is equal to the one specified as an argument. It unsets it from the session array. I just used the actual index where the username and ip is stored, so that those will be both unset, and the actual index will be unset too. Because if you just unset the  username and ip individually. The index where they are stored is just emptied but still exist.

function unset_session($uname){
	foreach($_SESSION['log_users'] as $id=>$lu){
	
		if($lu['username']==$username)){
			unset($_SESSION['log_users'][$id]);
		}
	}
}

 

Building the login form
Create a new php file, then paste this code:

<form id="form1" name="form1" method="post" action="loginForm.php">
  <label for="username">Username:</label>
  <input type="text" name="username" id="username" />
  <br />
  <label for="password">Password:</label>
  <input type="text" name="password" id="password" />
  <br />
  <input type="submit" name="login" id="login" value="login" />
<br />
</form>

Next, import the classes which we made earlier, and initialize them by declaring an object:

require_once('class.users.php');
require_once('class.sessions.php');
$users = new users();
$sessions = new sessions();

Then, check if the POST array is not empty. So that the codes that we will put inside will only be executed if the POST array has contents:

if(!empty($_POST)){

}

Inside of that condition, we then assign data extracted from the POST array to a variable:

$uname = $_POST['username'];
$pword = md5($_POST['password']);
$ip = $_SERVER['REMOTE_ADDR'];

The passwords that are stored in the database are hashed, so we need to call the md5 function or whatever function we used to hash the password before we submit it to any functions.
We then call the check_user() function from the user class. And assign the value which has been returned to the variable $exist:

$exist = $users->check_user($uname, $pword, $ip);

Next, we call the user_check() function from the users class and set the returned value to the variable $active. There are only 2 possible values here, 1 and 0. The function will return 1 if the username specified as an argument has an active value of 1. Otherwise it returns 0.

$active = $users->check_active($uname);

We then issue another condition, this will check if the value returned by check_user() function is equal to 1. And that the check_active() function returns a value except 1.

if(($exist == 1)&&($active != 1)){

}

Inside the condition, we call the create_session() function from the sessions class:

$sessions->create_session($uname, $ip);

What this does is to add the current user into the session array. It stores both the ip and the username, so that if somebody tried to access the page in a different computer with the same username. Then it won’t be able to view the user page since the user is already logged in somewhere else.

Then we create a cookie, which stores the current username and ip address in the local machine. In case you don’t know, cookies are stored in the local machine and sessions are stored in the server. If you are developing and testing it on the same machine where you are developing then there’s really not much difference since your local machine and server is the same. The only difference is that the cookie might be stored inside a folder in the browser. And the session is stored inside a folder in the web server.

setcookie("user", $uname, time()+900);
setcookie("ip", $ip, time()+900);

The cookie above will expire after 15 minutes. Which means, the user will have to log in every 15 minutes. Just change the value that is being added to the current time if you want it to be longer.
Then we call the set_last_login() function from the user class:

$users->set_last_login($uname);

After that, we just call the set_active() function from the user class. This will switch the status of the user to active or 1.

$users->set_active($uname);

Lastly, just redirect the page to the actual page that can only be accessed by users who are logged in:

header('Location:userpage.php');

 

Userpage

Next, create another php file. Name it to userpage.php or anything similar.
Import the session class again, then declare an object of it:

require_once('class.sessions.php');
$sessions = new sessions();

Then check if the cookie that we set upon log in exists. Then if those values exist, it assigns them to a variable:

if(!empty($_COOKIE['user'])&&($_COOKIE['ip'])){
	$username = $_COOKIE['user'];
	$ip = $_COOKIE['ip'];
}

If it doesn’t exist, then just put an else statement which will redirect the page into the login page:

else{
	header('Location:loginForm.php');
}

Then we call the check_session() function from the sessions class. And assign the returned value into the $active variable:

$active = $sessions->check_session($username, $ip);

Create another condition which checks if the $active has a value of 1:

if($active == 1){

}

Everything that is not supposed to be accessed by users who are not logged in goes inside of the condition above. First, let’s do the usual thing, greeting the user who is logged in:

echo 'userpage';
echo '<hr/>';
echo 'Hi! '. $username;

Then create a link which logouts the user:

<a href="userpage.php?logout=1&user=<?php echo $username; ?>">Logout</a>

The code below is then executed if the user clicks on the logout link:

if(!empty($_GET['logout'])){ $sessions->unset_session($username); setcookie("user", "", time()-9999999); setcookie("ip", "", time()-9999999);

$users->set_inactive($username); header('Location:loginForm.php'); }

On the 2nd line, we just call the unset_session() function inside the sessions class. We just assigned the username fetched from the $_COOKIE[‘user’] variable.
3rd and 4th line, we unset the user and ip cookie. That is by setting the cookie expiration date in a time in the past. I couldn’t think of a number so I just put 999999.
5th line, we just switch back the value of the active field for the corresponding user. This means that the user is already logged out or inactive.
6th line, we just redirect to the loginForm.

 

Conclusion
That’s it for this tutorial. The codes above are not in any way optimized or is the best way to do things. I will suggest that you don’t only use the ip address , username and password to authenticate the user. You might as well generate a unique string of characters and place it in the session as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s