Today post I want to share a little idea to avoiding two or more different user login using the same user ID or username in one application, this feature might be implemented in some specific application that have many restriction and tracking of logged user action in the system. In this post I am not showing any full code to test, just my simple thought.
The users table is most commonly used name in application, and the typical column name are id, username, password, first_name, last_name, etc. My idea is to adding one more field in users table that flagging if the user logged in or not. The simple SQL query might be something like this code below.
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `is_logged_id` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The flag column in this example is is_logged_id field set to INT type with one length, this will only consist the value between 1 (user logged in) or 0 (user not logged in).
I will use a little PHP code to illustrated this section. Most login application form use http post method to sent two common variable (username and password), in PHP we can access these variable using $_POST['var_name'], and you can use this step
1. Check whether user exist in database, and check whether user is logged in
$sql = "SELECT * FROM users WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."' AND is_logged_id = 0";
2. If a result found typically user id and username are registered is session variable using $_SESSION, and to preventing login with the same ID you have to update is_logged_in field
// register a variable to session $_SESSION['username'] = $_POST['username']; // update is_logged_in field $sql = "UPDATE users SET is_logged_in = 1 WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."'";
That is all, really simple you can customize to login error dialog and giving a message for example “someone already login using this account” or maybe a more advance feature like break the current session and force logged in. After user loggout make the is_logged_in field value back to zero.
There is a possible condition that the user may forgot to click the logout link in your system, which mean make the is_logged_in field still have 1 value, so to protecting a restricted page make sure you check the session first before, checking the database.