/    Sign up×
Community /Pin to ProfileBookmark

Can’t view session cookie.

Hi, I’m trying to design a login system using a session cookie to determine if a user is logged in or not, and am having a problem where the $_COOKIE[‘cookiename’] variable isn’t set according to subsequent pages. Here’s the code for the page that sets the cookie.

[code=php]
<?php
//set $_POST and $_GET to actual variables
require(“../includes/set.inc”);

/*
if this is the result of a login, verify credentials.
*/
if (isset($username)) {
mysql_connect(‘localhost’,’username’,’password’) or die (“Couldn’t connect to database: ” . mysql_error());
mysql_select_db(‘rewater’) or die (“Couldn’t select database.”);

$query = “select * from users where login=’$username’;”;
$result = mysql_query($query) or die (“Query failed: ” . mysql_error());
$array = mysql_fetch_array($result);
$loggedin = false;
if (isset($password)) {
if (crypt($password,”rw”) == $array[“password”]) {
$loggedin = true;
} else {
$err = “badpass”;
}
}
mysql_free_result($result);

if ($loggedin == true) {
//create a cookie’s session data
$cookiedata = generateData();
//set the cookie
setcookie(“cookiename”,$username.”::”.$cookiedata);

//update database entry
$query = “UPDATE users SET sessiondata='”.$cookiedata.”‘ WHERE login='”.$username.”‘;”;
mysql_query($query) or die (“Query failed: ” . mysql_error());
//proceed to the logged in page
header(“Location: page2.php”);
}
}
if (isset($err) && $err != “”) {
echo “Error: “;
if ($err == “badpass”) {
echo “Bad username/password combination. n”;
} else if ($err == “nologin”) {
echo “Your login cookie has expired. Please login again.”;
} else if ($err == “nocookie”) {
echo “No login cookie exists. If you are sure you are logged in, check you have cookies enabled.”;
} else if ($err == “logout”) {
echo “Logged out successfully.”;
}
}

function generateData($nSize=24) {
// Randomize
mt_srand ((double) microtime() * 1000000);
for ($i=1; $i<=$nSize; $i++) {

$nRandom = mt_rand(1,30);
if ($nRandom <= 10) {
// Uppercase letters
$sessionID .= chr(mt_rand(65,90));
} elseif ($nRandom <= 20) {
$sessionID .= mt_rand(0,9);
} else {
// Lowercase letters
$sessionID .= chr(mt_rand(97,122));
}
}
return $sessionID;
}
?>
<form action=”login.php” METHOD=”POST”>
Username: <input type=”text” name=”username”><BR>
Password: <input type=”password” name=”password”><BR>
<input type=”submit” value=”Submit”>
</FORM>
[/code]

And the code that checks the cookie data against what’s in the database is as follows:

[code=php]<?php
if (isset($_COOKIE[“cookiename”])) {
//get data out of cookie (stored as plaintext) and ensure it is right.
$checkstring = explode(“::”,$_COOKIE[“cookiename”]);

//open/read database entry.
mysql_connect(‘localhost’,’username’,’password’) or die (“Couldn’t connect to database: ” . mysql_error());
mysql_select_db(‘rewater’) or die (“Couldn’t select database.”);
$query = “SELECT sessiondata FROM users WHERE login='”.$checkstring[0].”‘;”;
$result = mysql_query($query);
$array = mysql_fetch_array($result);

if ($array[“sessiondata”] != $checkstring[1]) {
//cookie data doesn’t match – back to login page.
header(“Location: ../login/login.php?err=nologin”);
}
mysql_free_result($result);
mysql_close();
} else {
//return to login page if no cookie exists.
header(“Location: ../login/login.php?err=nocookie”);
}
?>[/code]

Theoretically this should all work – I’ve used much the exact same code before, and it has worked. The problem I’m getting is that the $_COOKIE[“cookiename”] variable doesn’t appear to be set. Checking the cookies in Firefox shows the call to setcookie() is working and putting the right data in there in the right places. Also checking the database shows that the session data is being updated, and doing an “echo” tracewrite immediately after the cookie is set also shows that the cookie is there. It is when it goes to the next and subsequent pages, and verifies it that the cookie can’t be found. Putting an “echo ‘cookie is ‘.$_COOKIE[“cookiename”]’; ” on the subsequent pages prints out “cookie is “.

Any tips/suggestions/ideas?

PHP is version 4.4.0.

Thanks, Chris. ?

to post a comment
PHP

8 Comments(s)

Copy linkTweet thisAlerts:
@SpectreReturnsSep 15.2005 — I'd use SESSION myself. Try this though:
[code=php]
print_r($_COOKIE);
[/code]
Copy linkTweet thisAlerts:
@Chris_J_WauthorSep 15.2005 — Oh, sorry, I tried that too, and it prints:

Array()

as the output, which I found quite weird considering I thought print_r was meant to print the contents of it's argument...which would imply perhaps the array is somehow being returned empty from $_COOKIE ?
Copy linkTweet thisAlerts:
@bokehSep 15.2005 — are you sure you used print[B]_r[/B]();
Copy linkTweet thisAlerts:
@SpectreReturnsSep 16.2005 — Guess what. That means your cookies aren't working. Try this:
[code=php]
setcookie("test", "test");
print_r($_COOKIE);
[/code]
Copy linkTweet thisAlerts:
@Chris_J_WauthorSep 19.2005 — LoL, yeah I figured out that bit (cookies aren't working). Okay, using the following code:

[code=php]<?php
//set $_POST and $_GET to actual variables
require("../includes/set.inc");

/*
if this is the result of a login, verify credentials.
*/
if (isset($username)) {
mysql_connect('localhost','username','password') or die ("Couldn't connect to database: " . mysql_error());
mysql_select_db('rewater') or die ("Couldn't select database.");

$query = "select * from users where login='$username';";
$result = mysql_query($query) or die ("Query failed: " . mysql_error());
$array = mysql_fetch_array($result);
$loggedin = false;
if (isset($password)) {
if (crypt($password,"rw") == $array["password"]) {
$loggedin = true;
} else {
$err = "badpass";
}
}
mysql_free_result($result);

if ($loggedin == true) {
//create a cookie's session data
$cookiedata = generateData();
//set the cookie
setcookie("cookiename",$username."::".$cookiedata);
//PRINT COOKIE ARRAY !!!
print_r($_COOKIE);

//update database entry
$query = "UPDATE users SET sessiondata='".$cookiedata."' WHERE login='".$username."';";
mysql_query($query) or die ("Query failed: " . mysql_error());
//proceed to the logged in page
header("Location: page2.php");
}
}
if (isset($err) && $err != "") {
echo "Error: ";
if ($err == "badpass") {
echo "Bad username/password combination. n";
} else if ($err == "nologin") {
echo "Your login cookie has expired. Please login again.";
} else if ($err == "nocookie") {
echo "No login cookie exists. If you are sure you are logged in, check you have cookies enabled.";
} else if ($err == "logout") {
echo "Logged out successfully.";
}
}

function generateData($nSize=24) {
// Randomize
mt_srand ((double) microtime() * 1000000);
for ($i=1; $i<=$nSize; $i++) {

$nRandom = mt_rand(1,30);
if ($nRandom <= 10) {
// Uppercase letters
$sessionID .= chr(mt_rand(65,90));
} elseif ($nRandom <= 20) {
$sessionID .= mt_rand(0,9);
} else {
// Lowercase letters
$sessionID .= chr(mt_rand(97,122));
}
}
return $sessionID;
}
?>
<form action="login.php" METHOD="POST">
Username: <input type="text" name="username"><BR>
Password: <input type="password" name="password"><BR>
<input type="submit" value="Submit">
</FORM>[/code]


Using the above code, I get the same result as I said above for the print_r($_COOKIE) statement (ie it outputs "Array( )"). However, after filling out the form a second time, it actually prints out
Array ( [cookiename] => login::Z6vV9JEZyG52sgoH870Mi32g )[/QUOTE]

Going on to the next page which checks the cookie is still getting "Array( )" for the print_r($_COOKIE) though.
Copy linkTweet thisAlerts:
@Chris_J_WauthorSep 19.2005 — Okay, having started mostly from scratch with this, I'm still having the same problem. Here's a (hopefully) more comprehensive description of it.

/login/login.php:
[code=php]<?php
require("../includes/set.inc");

/*
login.php:

check if already logged in
if so, then go to staff/index.php
else show login form, and proceed to processlogin.
*/
if (isset($_COOKIE["cookiename"])) {
//get data out of cookie (stored as plaintext) and ensure it is right.
$checkstring = explode("::",$_COOKIE["cookiename"]);

//open/read database entry.
mysql_connect('localhost','user','pass') or die ("Couldn't connect to database: " . mysql_error());
mysql_select_db('database') or die ("Couldn't select database.");
$query = "SELECT sessiondata FROM users WHERE login='".$checkstring[0]."';";
$result = mysql_query($query);
$array = mysql_fetch_array($result);

if ($array["sessiondata"] != $checkstring[1]) {
//cookie data doesn't match - back to login page.
header("Location: login.php?err=nologin");
}
mysql_free_result($result);
mysql_close();
header("Location: ../index.php");
}

if (isset($err) && $err != "") {
echo "Error: ";
if ($err == "badpass") {
echo "Bad username/password combination. n";
} else if ($err == "nologin") {
echo "Your login cookie has expired. Please login again.";
} else if ($err == "nocookie") {
echo "No login cookie exists. If you are sure you are logged in, check you have cookies enabled.";
} else if ($err == "logout") {
echo "Logged out successfully.";
}
}
?>
<form action="processlogin.php" METHOD="POST">
Username: <input type="text" name="username"><BR>
Password: <input type="password" name="password"><BR>
<input type="submit" value="Submit">
</FORM>[/code]


As described in the comments at the top of the file, basically it checks if the user is already logged in by looking for a cookie, and if so, redirects them to the logged in section. If not, it displays the login form. Anyway, assuming the form was filled out, it then proceeds onto the following file:

/login/processlogin.php:
[code=php]<?php
require("../includes/set.inc");
/*get variables
1. get record from database matching username
2. check pasword matches crypted password
3. set a cookie.
4. proceed to staff/index.php
*/

mysql_connect('localhost','user','pass') or die ("Couldn't connect to database: " . mysql_error());
mysql_select_db('database') or die ("Couldn't select database.");

$query = "select * from users where login='$username';";
$result = mysql_query($query) or die ("Query failed: " . mysql_error());
$array = mysql_fetch_array($result);

if (crypt($password,"rw") == $array["password"]) {
//create a cookie's session data
$cookiedata = generateData();

//set the cookie
setcookie("cookiename",$username."::".$cookiedata);

//update database entry
$query = "UPDATE users SET sessiondata='".$cookiedata."' WHERE login='".$username."';";
mysql_query($query) or die ("Query failed: " . mysql_error());

header("Location: ../index.php");
} else {
$err = "badpass";
header("Location: login.php?err=badpass");
}

mysql_free_result($result);

function generateData($nSize=24) {
// Randomize
mt_srand ((double) microtime() * 1000000);

for ($i=1; $i<=$nSize; $i++) {
$nRandom = mt_rand(1,30);
if ($nRandom <= 10) {
// Uppercase letters
$sessionID .= chr(mt_rand(65,90));
} elseif ($nRandom <= 20) {
$sessionID .= mt_rand(0,9);
} else {
// Lowercase letters
$sessionID .= chr(mt_rand(97,122));
}
}
return $sessionID;
}
?>[/code]


The above file then proceeds to verify the login credentials, and (assuming all is correct), continue onto the logged in index page.

Now continuing onto the logged in index page is where my problem is occuring. The header to there works fine, and once there, I have a call to a script (check.inc) containing much the same code as login.php to verify that the user is actually logged in with a cookie as follows:

/index.php:
[code=php]
<?php
require("includes/check.inc");
include("includes/sections.php");
dispTop("images/headerfrontpage.jpg","Staff Section","..");
?>
<!--Actual content here-->
<H2 style="margin-top: 0;">Staff</H2>
Use the menu to the left to select the appropriate action you want to perform.
<?php dispMiddle("#A42212"); ?>

<!--right side images/mouseovers go here-->

<?php dispBottom(); ?>
[/code]


As I said above, the check.inc script performs a similar check to the first part of login.php above to ensure that the user has a session cookie matching their stored session data in the database as follows:

/includes/check.inc
[code=php]
<?php
//check cookie is set, and that it's data matces that we have stored in the database.
if (isset($_COOKIE["cookiename"])) {
//get data out of cookie and ensure it is right.
$checkstring = explode("::",$_COOKIE["cookiename"]);

//open/read database entry.
mysql_connect('localhost','user','pass') or die ("Couldn't connect to database: " . mysql_error());
mysql_select_db('database') or die ("Couldn't select database.");
$query = "SELECT sessiondata FROM users WHERE login='".$checkstring[0]."';";
$result = mysql_query($query);
$array = mysql_fetch_array($result);

if ($array["sessiondata"] != $checkstring[1]) {
//cookie data doesn't match - back to login page.
header("Location: ../login/login.php?err=nologin");
}
mysql_free_result($result);
mysql_close();
header("Location: ../index.php");
} else {
//return to login page if no cookie exists.
header("Location: ../staff/login/login.php?err=nocookie");
}
?>
[/code]


This is where things are having problems. According to index.php, $_COOKIE is empty (output from "print_r($_COOKIE);" is "Array ( )"). As such, it is failing the check and redirecting back to login.php. Once the redirect back to login.php happens, the check on login.php is being performed, and the cookie is being found, so the user is redirected to the logged in index page. As you can probably see, this degenerates into a cycle between the login.php and index.php pages with the cookie found on login.php and apparently missing on index.php, and I end up with a "too many redirections" error.

Any ideas/suggestions would be fantastic!
Copy linkTweet thisAlerts:
@Chris_J_WauthorSep 20.2005 — Can't believe I didn't check this sooner - I solved the problem. When I was calling setcookie(), since I wasn't specifying a path, it was defaulting to /login for the cookie being valid on, and when this went to / then the cookie wasn't valid, and such it failed to find it and reset it. Thanks for the help.
×

Success!

Help @Chris_J_W spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...