just switched from cookies to sessions

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

just switched from cookies to sessions

Post by s.dot »

Okay, i just did the switch from using cookies to using sessions. I'm not familiar at all so could someone please tell me how secure my setup is?


Processing the login

Code: Select all

/* User is logging in from index.php */
if($_POST['action'] == "login")
{
	$username = mysql_real_escape_string(strip_tags($_POST['username']));
	$password = md5(mysql_real_escape_string(strip_tags($_POST['password'])));
	
	$result = mysql_query("SELECT id, username, activated FROM users WHERE username = '$username' AND password = '$password'") or die(mysql_error());
	
	if(mysql_num_rows($result) < 1)
	{
		header("Location: index.php?loginerror=1");
	}
	
	if(mysql_num_rows($result) == 1)
	{
		$row = mysql_fetch_assoc($result);
		
		if($row['activated'] == "n")
		{
			header("Location: index.php?loginerror=2");
		}
		
		$_SESSION['username'] = $row['username'];
		
		mysql_query("UPDATE users SET  session = '".session_id()."' WHERE username = '{$row['username']}'") or die(mysql_error());
  		
		header("Location: index.php");
	} ELSE
	{
		die("There has been an unknown error.  Please inform the webmaster of this message and the time this error occured.");
	}
}
Included check on every page

Code: Select all

if(isset($_SESSION['username']))
{
     // store session name in variable
	$theperson = $_SESSION['username'];

     // get the session id that was generated and stored in the database during login
	$sessiondba = mysql_fetch_assoc(mysql_query("SELECT session FROM users WHERE username = '$theperson'"));
	$sessiondb = $sessiondba['session'];
	
     // get current session id
	$session = session_id();

     // check to see if database session id matches current session id
	if($sessiondb != $session)
	{
		$_SESSION = array();
		if (isset($_COOKIE[session_name()]))
		{
			setcookie(session_name(), '', time()-42000, '/');
		}
		session_destroy();
		header("Location: index.php");
		die();
	}
}
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply