Problem Setting Cookies


I have a login screen and when the user clicks the login button it goes
to my php script where I check the database to validate the login creds.
Then I want to set a cookie. I am having such a diffcult time doing this.
I was wondering if something could help me out.

here is part of my code - anyways the cookie is not getting set.
what have I done wrong?

$sUser = $_GET[‘user’];
$sPwd = $_GET[‘pwd’];

setcookie(“user”, $sUser, time()+3600);
setcookie(“user”, $sPwd, time()+3600);

if (isset($_COOKIE[“user”]))
echo "Welcome " . $_COOKIE[“user”] . “!<br />”;
echo “Welcome guest!<br />”;

Couple of things…

Cookie are not available immediately after setting them, it requires a new request.

Basically you need to redirect them or reload the page in order to see the value in $_COOKIE.

If that’s not your problem then try adding the 4th and 5th parameters for the cookie

setcookie(‘user’, $sUser, time() + 3600, ‘/’, $_SERVER[‘HTTP_HOST’])

will usually do the job.

Also a cookie is a single plain text string, therefore if you set $sUser, then do another setcookie with $sPwd, it will only store the pwd, so you need to serialize if you need to store an array of values. Or at the very least separate them with a predefined character, like | (pipe) and split it internally.

Storing passwords in cookies isn’t really good practice of security, this is why most sites only store your username and make you re-enter your password.