Forum Moderators: coopster

Message Too Old, No Replies

Set cookie with JS, retrieve it with PHP

Strangely it does not work

         

cameraguy

1:52 pm on Jul 16, 2005 (gmt 0)

10+ Year Member



This is driving me crazy because it shouldn't cause a problem:

I can't seem to retrieve in PHP a cookie created in JS.

function setCookie(name, value, expires, path, domain, secure)
{
document.cookie= name + "=" + escape(value) +
((expires)? "; expires=" + expires.toGMTString() : "") +
((path)? "; path=" + path : "") +
((domain)? "; domain=" + domain : "") +
((secure)? "; secure" : "");
}

function check_admin(password)
{
var password_entered = prompt("Please enter your password for administrator privileges.", "");
var password = document.get_password.password.value ;
if (password_entered == password)
{
setCookie("new_cookie", "correct");
}
else
{
setCookie("new_cookie", "wrong");
}
}

<?
$new_cookie = $HTTP_COOKIE_VARS["new_cookie"];
echo $new_cookie;
?>

When I reload the page $new_cookie is empty!

Can anyone figure out why?

Thanks!

gliff

2:40 pm on Jul 16, 2005 (gmt 0)

10+ Year Member



I mocked up a page and the "set in js, read in php" cookie code worked for me.

How are you calling the javascript? Is "document.get_password.password.value" defined? Chances are the javascript is failing for some reason, and the cookie is never being set.

Download Firefox, load you page, and go to Window->Javascript Console. Click the clear button. Reload your page and go through your password setting and see what, if any, errors show up in the console.

cameraguy

4:19 pm on Jul 16, 2005 (gmt 0)

10+ Year Member



Thanks for giving it a try.

var password = document.get_password.password.value

...is defined by...

<form name="get_password" action="#">
<input type="hidden" name="password" value="<?=$password?>">

That's how I pass the password variable from php to js.

Other than that, I get no errors on the JS console of Firefox. And the cookies exist, because after setting them, I manage to retrieve and print them in the js script.

dcrombie

9:35 am on Jul 17, 2005 (gmt 0)



After the cookie is set using JavaScript, the server (where your PHP is running) still doesn't know about it. It's only on the _next_ request to that domain that the cookie values are sent in the request headers.

cameraguy

4:49 pm on Jul 17, 2005 (gmt 0)

10+ Year Member



That makes sense. Thank you!