PHP Authentication to prevent multiple logins

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

PHP Authentication to prevent multiple logins

Post by cjkeane »

Hi everyone.

I'm trying to develop an authentication script to prevent multiple logins. My issue is that, I think it might not be the best route to go. I'm looking for some feedback. Any help would be appreciated. Thanks.

the login script:

Code: Select all

ob_start();
	session_start();
	require_once('config/db.inc');
	require_once('config.php');
	$errmsg_arr = array();
	$errflag = false;
	function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}
	$login = clean($_POST['login']);
	$password = clean($_POST['password']);
	if($login == '') 	{$errmsg_arr[] = 'Login ID missing';$errflag = true;}
	if($password == '') {$errmsg_arr[] = 'Password missing';$errflag = true;}
	if($errflag) {
		$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
		session_write_close();
		header("location: index.php");
		exit();
	}
	$qry="SELECT * FROM caseowner WHERE RequestedUserName='$login' AND DefaultPassword='".md5($_POST['password'])."'";
	$result=mysql_query($qry);
	if($result) {
		if(mysql_num_rows($result) == 1) {
			session_regenerate_id();
			$member = mysql_fetch_assoc($result);
			$_SESSION['SESS_MEMBER_ID'] = $member['CaseOwnerSelectID'];
			$_SESSION['SESS_FIRST_NAME'] = $member['UserNameFirst'];
			$_SESSION['SESS_LAST_NAME'] = $member['UserNameLast'];
			$_SESSION['SESS_USERNAME'] = $member['RequestedUserName'];
			$_SESSION['SESS_AUTHCHECK'] = $member['MarkForAuthentication'];
			$_SESSION['SESS_USERS_EMAIL'] = $member['UserEMail'];
			$_SESSION['SESS_USERS_EMAIL2'] = $member['UserEMail2'];
			$_SESSION['SESS_USERS_SIG'] = $member['UserSignature'];
			$_SESSION['SESS_USERS_SIG2'] = $member['UserSignature2'];
			$_SESSION['SESS_ACL1'] = $member['ACL1'];
			$_SESSION['SESS_ACL2'] = $member['ACL2'];
			$_SESSION['SESS_ACL3'] = $member['ACL3'];
			
			// insert the users session id into their user account using md5
			$users_session = md5(session_id());
			$datetime = date('Y-m-d'); // = yyyy-mm-dd
			$update_users_session_in_their_account = mysql_query("UPDATE caseowner SET session_id='$users_session', LastLoginDate='$datetime' WHERE RequestedUserName='$login' AND DefaultPassword='".md5($_POST['password'])."' ");
			
			if ($update_users_session_in_their_account ) {
				// end session id update in user account
				echo '<img src="images/loading-spinner.gif" height="25" width="25" style="float:left; padding-right: 20px;">';
				echo '<div style="color:red;" align="left">Session information and login date have been successfully recorded! Please wait for page re-direct.</div><br />';
				$page ="index_home.php";
				header("Refresh: 3; url=$page");
				exit(); 
			} else {
				echo '<img src="images/loading-spinner.gif" height="20" width="20" style="float:left; padding-right: 20px;">';
				echo '<div style="color:red;" align="left">There was an error recording session information in the database! Please wait for page re-direct.</div><br />';

				//echo "Error updating session info in user account for: " . $_SESSION['SESS_FIRST_NAME'] = $member['UserNameFirst'] . " " . $_SESSION['SESS_LAST_NAME'] = $member['UserNameLast'] . " has failed.";
				$page ="login-failed.php";
				header("Refresh: 5; url=$page");
				exit();
			}
			session_write_close();
		}
	} else {
		die("Access Denied: User Cannot was not found in database.");
		$page ="index.php";
		header("Refresh: 5; url=$page");
		exit();
	}
the auth code:

Code: Select all


	session_start();
	if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '') || (trim($_SESSION['SESS_AUTHCHECK'] == 'No'))) {
		header("location: access-denied.php");
		exit();
	} else {
		//Prevent multiple logins
		if (isset($_SESSION['SESS_MEMBER_ID'])) {
			$result = mysql_query('SELECT COUNT(*) FROM caseowner WHERE CaseOwnerSelectID='.$_SESSION['SESS_MEMBER_ID']." AND session_id='".mysql_real_escape_string(md5(session_id()))."'");
			$login_status = mysql_result($result,0,0);
			if (0 == $login_status) {
				unset($_SESSION['SESS_MEMBER_ID']);
				unset($_SESSION['SESS_FIRST_NAME']);
				unset($_SESSION['SESS_LAST_NAME']);
				setcookie(session_name(), '', time()-300, '/', '', 0); //destroy the cookie
				echo 'You are already logged on. Only one login per user account is permitted. Login refused';
				$page ="index.php";
				header("Refresh: 5; url=$page");
				exit();
			 }
		}
	}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP Authentication to prevent multiple logins

Post by requinix »

Only two parts are actually required:
1. When the user logs in, track the session ID with their information in the database
2. On every page load, verify that the current session ID matches the one with the user or else log them out

Anything else is up to you and your application.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP Authentication to prevent multiple logins

Post by cjkeane »

thanks for your message. I tried my code and I was expecting logging in with a different browser would display the 'You are already logged in' message but it didn't. I think I was coding it the way you suggested. I think it will always allow the user because i check the username and password and if it matches, i update the session_id in the db.. I'm not sure how i should re-code it..

i include the auth.php at the top of every page. i just need to compare the logged in session_id with the one stored in the db.. and suggestions?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP Authentication to prevent multiple logins

Post by requinix »

You don't have anything to check when logging in.

1. Log in with browser A (okay)
2. Browse in A (okay)
3. Log in with browser B (okay)
4. Browse in B (okay)
5. Browse in A (not okay)

It's the old session that gets kicked out. Do you want to block new logins too? That will be a bit more work...
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP Authentication to prevent multiple logins

Post by cjkeane »

i want to only allow 1 user to log in with their account. i dont want them to login with another browser or device.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP Authentication to prevent multiple logins

Post by requinix »

Then prohibit logging in when there's a session ID set and you don't consider the session to be abandoned (eg, last browsing activity was >X minutes ago, which implies tracking that).

Keep in mind what you're doing will prevent someone from logging into their account if they somehow lose their previous session, such as close their browser. If you use the second condition above then at least they can get in by waiting for X minutes, but if you don't then they'll be totally locked out.

If you think I'm suggesting that this is a bad idea, you're right.
Post Reply