Jump to content

Session Help


RyanMinor

Recommended Posts

To my understanding, a session is created and then stored on the server with its assigned value and a unique id. So, if that is correct I should be able to somehow locate a particular session on the server based on it's assigned value. Well, I was hoping to use this concept to keep multiple people from logging in under the same account at the same time.

 

I figured that I could check this in my login script by declaring the customer's id as the session value when they login. Then, I could check for a session variable equal to the cusotmer's id when they try to login. My (untested) code is below. Am I going about this right, and how would I check to see if a user's session is currently set on the server?

 


<?php
// initiate session and redirect logged in users
session_start();
if(isset($_SESSION['customer_id'])) {
header('location:my_videos.php');
}

// if login button was pressed
if(array_key_exists('login', $_POST)) {
// initalize error array and check that user supplied a username and password
$error = array();
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(empty($username)) {
	$error['username'] = 'Please enter your username.';
}		
if(empty($password)) {
	$error['password'] = 'Please enter your password.';
}
// if username and password supplied then proceed
if(!$error) {
	// connect to the database
	require_once('includes/connect.php');
	// filter data for query
	$username = mysql_real_escape_string($username);
	$password = md5(mysql_real_escape_string($password));
	$queryUser = mysql_query("SELECT customer_id, customer_username, customer_password FROM customer WHERE customer_username = '$username' AND customer_password = '$password'", $connect) or die(mysql_error());
	$dataUser = mysql_fetch_assoc($queryUser);
	$rowsUser = mysql_num_rows($queryUser);
	$customerId = $dataUser['customer_id'];
	// determine if the user is a valid customer
	if($rowsUser == 1) {
		// see how many IP addresses the customer has used to login with in the past 24 hours
		$queryIP = mysql_query("SELECT COUNT(DISTINCT log_ip) AS ip FROM log WHERE log_customer_id = $customerId AND log_timestamp IN((DATE_SUB(NOW(), INTERVAL 1 DAY)), NOW())") or die(mysql_error());
		$dataIP = mysql_fetch_assoc($queryIP);
		if($dataIP['ip'] > 3) {
			$error['ip'] = 'This customer account has reached the maximum number of IP addresses allowed. If you feel this is a system error please send us an email via the Contact Us form.';
			exit;
		} else {
			// see if the customer is already logged in
			$queryLogged = mysql_query("SELECT customer_id, customer_logged_in FROM customer WHERE customer_logged_in = 1 AND customer_id = '$customer_id'", $connect) or die(mysql_error());
			$dataLogged = mysql_fetch_assoc($queryLogged);
			$rowsLogged = mysql_num_rows($queryLogged);
			if($rowsLogged == 1) { // if database shows the customer is already logged in
				// if there is also a session variable set that matches their customer id on the server
				if($_SESSION['customer_id'] == $customerId) { // i need to somehow find this session value on the server first
					// this means the user is trying to login from two different locations
					header('location:bad_login.php');
					exit;
				// if no session variable for customer id is set on the server	
				} else {
					// this means user lost connection without logging out
					// set a customer id session variable
					$_SESSION['customer_id'] = $customerId;
					// log customer activity
					$ip = $_SERVER["REMOTE_ADDR"];
					$queryLog = mysql_query("INSERT INTO log (log_timestamp, log_ip, log_customer_id) VALUES (NOW(), '$ip', '$customerId')", $connect)or die(mysql_error());
					// send user to appropriate page (if a previous page session variable exists send them there)
					if(isset($_SESSION['previous_page'])) {
						header('location:video_info.php');
					// if not send them to the my_videos.php page
					} else {
						header('location:my_videos.php');
					}
				}
			} 
			// if database shows the customer is not logged in
			else {
				$_SESSION['customer_id'] = $customerId;
				$queryLogin = mysql_query("UPDATE customer SET customer_logged_in = 1 WHERE customer_id = '$customerId'", $connect) or die(mysql_error());
				$ip = $_SERVER["REMOTE_ADDR"];
				$queryLog = mysql_query("INSERT INTO log (log_timestamp, log_ip, log_member_id) VALUES (NOW(), '$ip', '$customerId')", $connect)or die(mysql_error());
				if(isset($_SESSION['previous_page'])) {
					header('location:video_info.php');
				} else {
					header('location:my_videos.php');
				}
			}
		}
	// if there was no match found in the database	
	} else {
		$error['login'] = "Incorrect username and/or password. If you do not have an account with us, please create one";
	}		
}	
}		
?>

Link to comment
Share on other sites

You are going about this in the correct fashion. A couple of points.

 

1. A session can be lost when a user closes their web browser, re-opens and then goes back to the same page meaning they will have to re-login. One way to combat this is to set a cookie aswell as session data when a user logs in. If the session is lost after a browser close, the cookie isn't and this can be used to regenerate the session data.

 

2. When using sessions or cookies it is nice to add some security such as a hashed encryption string in with the session/cookie data. You have just used the customers ID. If you were to store that in a cookie then it could easily be stolen, so, when a user logs in an you test their username/password, if it is correct make a hash of something and store it in the users database table. When they log out destroy it from the database, after a period of inactivity destroy it also. Then on every page where a cookie or session is needed you can test the hash value against the customers ID and the hash stored in the database i.e.

 

/*
login successful
*/
$_SESSION['customer_id'] = $customer_id;
$_SESSION['customer_hash'] = md5($_SESSION['customer_name'].time());
/*
store the hash
*/
mysql_query("UPDATE customers SET customer_hash='".$_SESSION['customer_hash']."' WHERE customer_id='".$customer_id."'");
/*
redirect
*/
header('location:/my_videos.php');
exit();

 

On pages where you need to check the session is valid

 

if(isset($_SESSION['customer_id']) && strlen($_SESSION['customer_hash']))  {
$result = mysql_query("SELECT customers_id FROM customers WHERE customer_hash='".$_SESSION['customer_hash']."' AND customer_id='".$_SESSION['customer_id']."'");
if(mysql_num_rows($result)) {
  header('location:/my_videos.php');
  exit();
}
/*
session data is not valid
*/
header('location:/login.php');
exit();
}

 

3. Always use the exit() function after any header redirect as in the above examples.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.