Monday, March 24, 2008

PHP - SetCookie problem and solution

I have these two files :

login.php :
--------------------
setcookie("qq_user","john",time()+604800);
require "function.php";
justPrint();
----------------------

and function.php :

--------------------------------
function justPrint(){
if((isset($_COOKIE["qq_user"]))){
echo "Log Out";
}
else{
echo "Log In";
}
}
-------------------------------



Now when I invoke login.php, it should simply print Log Out, but it
prints out Log In.

I don't know what could the reason be. I thought the delay wasn't enough
between setCookie and justPrint, but inserting a significant delay with
the help of sleep function didn't change anything either.

Finally this worked :
I added one more file new.php.

Now following are the contents of the above 3 files :
login.php :

------------------------
setcookie("qq_user","john",time()+604800);

require "function.php";
header('Location: new.php');
-------------------------------

function.php remains the same.

new.php :
<?
require "function.php";
justPrint();
?>


It's strange why does it work, but it does.

1 comment:

Paladin said...

setcookie only send cookie to the browser, it does not change content of $_COOKIE array. So you must reload page when you what to se changes.

Blog Archive