Jump to content

"Remember Me" Session/Cookie problems.


Errant_Shadow

Recommended Posts

What I'm trying to accomplish is your average session login w/ a cookie-based "remember me" feature.

 

I can log in fine, I can set cookies, I can access those cookies, and I can use that data to log in just as if the user had logged in manually.

 

The problem is logging out. But the bigger problem is figuring out why.

 

You see, it works perfect. It logs in and it log out, so long as I am outputting data to the page. I was outputting a session variable and the cookies I set to make sure they were all working right; and they were. But then as soon as I disable those echoes, all of a sudden it won't log out anymore.

 

So then I turn them on to see what the data says and BAM, I'm logged out. I log back in fine, I log back out fine, so I turn em off again.

 

I log in fine. I can't log out. I try multiple times. I close my browser and open a new one. Still logged in. I try a few more times, still logged in. I turn the output back on, load the page again and I'm logged out.

 

So... WTF? (my code to follow)

Link to comment
Share on other sites

The log in form uses a little JavaScript to make sure the fields have data, then it passes that data to my log in script.

 

<form name="login" id="login" method="post">
<table border="0" style="font-size:14px;" align="CENTER">
	<tr align="center">
		<td colspan="2">
			<input class="rounded" type="text" name="email" id="email" onfocus="checkField(this.name)" onblur="setField(this.name)" style="width:400px; font-size:24px; background-image:url('forms/images/big-email.png');background-repeat:no-repeat;" value="" />
		</td>
	</tr>
	<tr align="center">
		<td colspan="2">
			<input class="rounded" type="password" name="pword" id="pword" onfocus="checkField(this.name)" onblur="setField(this.name)" style="width:400px; font-size:24px;  background-image:url('forms/images/big-pword.png');background-repeat:no-repeat;" value="" />
		</td>
	</tr>
	<tr align="left">
		<td width="1px">
			<img src="/forms/images/login-out.png" alt="submit" onmouseover="this.src='/forms/images/login-over.png';" onmouseout="this.src='forms/images/login-out.png';" onclick="submitForm()" />
		</td>
		<td>
			<input type="checkbox" name="rem_me" id="rem_me" /> Remember Me<br />
			<div style="font-size:10px; padding-left:4px"><a href="/?p=login&a=reset">Forgot your Log in Information?</a></div>
		</td>
	</tr>
</table>
</form>

<script type="text/javascript">
<!--

// trim function
function myTrim(stringToTrim) 	{ return stringToTrim.replace(/^\s+|\s+$/g,""); }

//	 ####   ##  ##  ######   ####   ##  ##  ######  ######  ######  ##      #####   
//	##   #  ##  ##  ##      ##   #  ## ##   ##        ##    ##      ##      ##  ##  
//	##      ######  ####    ##      ####    ####      ##    ####    ##      ##  ##  
//	##   #  ##  ##  ##      ##   #  ## ##   ##        ##    ##      ##      ##  ##  
//	 ####   ##  ##  ######   ####   ##  ##  ##      ######  ######  ######  #####   
function checkField (field)
{

	//	alert("checkField("+ action +","+ field +")");

	var	myField	 = document.getElementById(field);
//	var	myValue	 = myTrim(myField.value);
	//	alert('myValue = '+ myValue);

	myField.style.backgroundImage = 'url("forms/images/big-default.png")'

}

//	 ####   ######  ######  ######  ######  ######  ##      #####   
//	##      ##        ##    ##        ##    ##      ##      ##  ##  
//	 ####   ####      ##    ####      ##    ####    ##      ##  ##  
//	    ##  ##        ##    ##        ##    ##      ##      ##  ##  
//	 ####   ######    ##    ##      ######  ######  ######  #####   
function setField(field)
{
	var	myField				 = document.getElementById(field);
	var	myValue				 = myTrim(myField.value);
	var	myBackgroundImage	 = false;

	if (myValue == "")
	{
		myBackgroundImage = true;
	}

	myField.style.backgroundImage	 =(myBackgroundImage)? 'url("forms/images/big-'+ field +'.png")' : 'url("forms/images/big-default.png")';
}

//	 ####   ##  ##  ######   ####   ##  ##  ######   ####   #####   #    #  
//	##   #  ##  ##  ##      ##   #  ## ##   ##      ##  ##  ##  ##  ##  ##  
//	##      ######  ####    ##      ####    ####    ##  ##  #####   # ## #  
//	##   #  ##  ##  ##      ##   #  ## ##   ##      ##  ##  ##  ##  #    #  
//	 ####   ##  ##  ######   ####   ##  ##  ##       ####   ##  ##  #    #  
function checkForm ()
{
	var	fields	 = new Array("email","pword");
	//	alert("fields = "+ fields);
	for (var thisField in fields)
	{
		var thisValue	 = document.getElementById(fields[thisField]).value;
		//	alert ("Checking "+ fields[thisField] +" ("+ thisValue +")");
		if (thisValue == "") return false;
	}

	return true;
}

// SUBMIT FORM
function submitForm ()
{
	var	email	 = myTrim(document.getElementById("email").value);
	var	pword	 = MD5(document.getElementById("pword").value);
	var	rem		 = document.getElementById("rem_me").checked;

	if (checkForm())
	{
	//	alert("Execute Log in Script...");

		// code for IE7+, Firefox, Chrome, Opera, Safari
		if (window.XMLHttpRequest) 	{ xmlhttp=new XMLHttpRequest(); }
		// code for IE6, IE5
		else { 	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

		xmlhttp.onreadystatechange=function()
		{
		//	alert('xmlhttp.onreadystatechange! (readyState = '+ xmlhttp.readyState +'; xmlhttp.status = '+ xmlhttp.status +')');
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
			//	document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

				var	response	 = xmlhttp.responseText;
				//	alert('login('+ email +', '+ pword +') responce = '+ xmlhttp.responseText);

				switch (response)
				{
					case "true":
						// document.forms["login"].submit();
						window.location.reload();
						break;

					case "no user":
						alert("Log in Failed! \n\nThe e-mail address and password you \nentered did not match our records.");
						break;

					case "unapproved":
						alert("Log in Failed! \n\nThat account is not yet approved.");
						break;

					default:
						alert("Log in Failed!\n\n"+ response);
						break;
				}

			}
		}

		$uri	 = "functions/login.php?e="+ email +"&p="+ pword +"&r="+ rem;
		xmlhttp.open("GET",$uri,true);
		xmlhttp.send();
	}
	else
	{
		alert("Form incomplete or inaccurate!");
	}
}

-->
</script>

Link to comment
Share on other sites

My log in script loads in the background, called by JavaScript. I know JS can be disabled, but it's enabled in my testing environment so that's not the problem.

 

Anyway, it checks for a connection and creates one if there is none.

 

Then it executes the log in function and outputs a return value if one is needed (depends on how the script is being called).

It checks for the value of $r (which was passed to the page through $_GET['rem_me'] when JS called this file.

 

If $r is true, it sets 3 cookies; uid, email, and pword (which is stored as an MD5 hash of whatever the user entered into the password field).

 

<?php
if (!isset($con))
{
	require_once("../functions/dbc.php");
	mysql_select_db($dbname, $con);

	$close_con		 = true;
	$print_output	 = true;
}

function login()
{
	$e=$_GET["e"];
	$p=$_GET["p"];
	$r=$_GET["r"];

	$sql="SELECT `uid`, `approved`, `email`, `username`, `ethnicity`, `country`, `region` FROM `users` WHERE `email` = '$e' AND `pword` = '$p'";
	//	echo 'Query: '. $sql .'<br />';

	$result		 = mysql_query($sql) or die(mysql_error());
	$user_data	 = mysql_fetch_array($result);

	if (!empty($user_data)) 
	{	//	uid, approved, email, username, ethnicity, country, region

		if ($user_data['approved'])
		{
			session_start();
			$_SESSION['uid']		 = $user_data['uid'];
			$_SESSION['email']		 = $user_data['email'];
			$_SESSION['username']	 = $user_data['username'];
			$_SESSION['ethnicity']	 = $user_data['ethnicity'];
			$_SESSION['country']	 = $user_data['country'];
			$_SESSION['region']		 = $user_data['region'];

			/*
			echo "<hr />SESSION:<br />";
			foreach($_SESSION as $key => $value) { echo $key .": ". $value ."<br />"; }
			echo "<hr />";
			*/
		}

		$sql = "
			UPDATE
				`users`
			SET
				`last_login` = NOW(),
				`last_ip` = '". $_SERVER['REMOTE_ADDR'] ."'
			WHERE
				`uid` = '". $_SESSION['uid'] ."'
			LIMIT 1";

		$result		 = mysql_query($sql) or die(mysql_error());

		if ($r == true)
		{
			setcookie("uid", $_SESSION['uid'], time() + (60*60*24*30), "/", ".virtuocracy.com");
			setcookie("email", $e, time() + (60*60*24*30), "/", ".virtuocracy.com");
			setcookie("pword", $p, time() + (60*60*24*30), "/", ".virtuocracy.com");
		}

		return "true";
	}
	else
	{
		return "no user";
	}
}

$output	 = login();

/*
if (!isset($print_output))
{
	echo "<hr />";
	echo "email = ". $_GET["e"] ."; ";
	echo "pword = ". $_GET["p"] ."; ";
	echo "rem = ". $_GET["r"] ."; ";
}
*/

if (isset($print_output)) echo $output;

if (isset($close_con)) mysql_close($con);
?>

 

This script is also called when the index page checks for those 3 cookies (which it only does when it finds no active session). As you can see, it also sets the GET variables so the function will work.

 

<?php
if (!isset($_SESSION['uid']) && (isset($_COOKIE['uid']) && isset($_COOKIE['email']) && isset($_COOKIE['pword'])))
{

	$_GET["e"]	 = $_COOKIE['email'];
	$_GET["p"]	 = $_COOKIE['pword'];
	$_GET["r"]	 = false;

	require_once("functions/login.php");
}
?>

Link to comment
Share on other sites

Finally, my log out function simply sets the cookies to expire, destroys the session, and reloads the site.

 

<?php
if (isset($_SESSION['uid']) && (isset($_GET['a']) && $_GET['a'] == 'logout'))
{
	// echo "<hr /><hr /><hr /><hr />logging out...";
	// delete cookie...
	setcookie("uid", "", time() - 3600, "/", ".virtuocracy.com");
	setcookie("email", "", time() - 3600, "/", ".virtuocracy.com");
	setcookie("pword", "", time() - 3600, "/", ".virtuocracy.com");

	if (ini_get("session.use_cookies"))
	{
		$params = session_get_cookie_params();
		setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
	}

	session_unset();
	session_destroy();
	header('Location: /');
}
?>

 

And of course, here's where it gets frustrating. I have a series of echoes that output data in between the logout code and the code that checks for cookies.

 

<?php

echo "<hr /><hr /><hr /><hr />";

echo "SESSION[uid] = ";
if (isset($_SESSION['uid'])) { echo $_SESSION['uid'] ."<br />"; }
else { echo "Unavailable!<br />"; }

echo "COOKIE[uid] = ";
if (isset($_COOKIE['uid'])) { echo $_COOKIE['uid'] ."<br />"; }
else { echo "Unavailable!<br />"; }

echo "COOKIE[email] = ";
if (isset($_COOKIE['uid'])) { echo $_COOKIE['email'] ."<br />"; }
else { echo "Unavailable!<br />"; }

echo "COOKIE[pword] = ";
if (isset($_COOKIE['uid'])) { echo $_COOKIE['pword'] ."<br />"; }
else { echo "Unavailable!<br />"; }

?>

 

So the page SHOULD load with the logout command (/?a=logout), it should log out, and the reload the page.

Which it does, but then the cookies log it right back in... unless those echoes are outputting data. So what are all the things I'm doing wrong here?

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.