Forum Moderators: coopster

Message Too Old, No Replies

Why is my cookie expiring.

Username & Password should expire after 3 months.

         

rike

1:47 am on May 11, 2010 (gmt 0)

10+ Year Member



I've adapted a php script which holds a username and password in a cookie which should expire after 3 months. (If username & pasword in the cookie is correct go to content page, & if incorrect or non-existant, go to login page.)

My cookie is doesnt last long and keeps taking me back to the login page instead of the content page, can anyone explain why.


This is the code that sets the cookie:

<?php
$formuser = $_POST["formuser"];
$formpass = $_POST["formpass"];
$expire = time() +60*60*24*90;
$formpass = md5($formpass);
if($formuser && $formpass) {
setcookie ("cookuser");
setcookie ("cookpass");

setcookie ("cookuser", $formuser, $expire);
setcookie ("cookpass", $formpass, $expire);
header("Location: docs.php");
}
else {
include("config.php");
echo($no_pass_or_user_error_message);
}
?>

Matthew1980

6:58 am on May 11, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there rike,

try this in the expire time:-

<?php
$formuser = strip_tags($_POST['formuser']);
$formpass = strip_tags($_POST['formpass']);
$expire = time()+60*60*24*30;
$formpass = md5($formpass);
if($formuser && $formpass) {
$cookieuser = "cookieuser";
$cookiepass = "cookiepass";

setcookie($cookieuser, $formuser, $expire);
setcookie($cookiepass, $formpass, $expire);//not a good idea putting a password in a cookie :/
header("Location: docs.php");
}
else {
include("config.php");
echo $no_pass_or_user_error_message;
}
?>

Your error was in this part:-

setcookie ("cookuser");
setcookie ("cookpass");

You were setting the cookie with no expire time, and then overwriting it, try the above, and it should work better now.

And I have put a bit of security over the $_POST globals, you can never be too careful :)

This will now set a cookie for 30 days.

Good luck,

Cheers,
MRb

arvind gupta

7:14 am on May 18, 2010 (gmt 0)

10+ Year Member



And as pointed out by Matthew1980, never save unencrypted passwords in cookies. I always hash them with md5 with salt.

rike

11:15 pm on May 18, 2010 (gmt 0)

10+ Year Member



Thanks Mathew.