...

View Full Version : $_COOKIE not working correctly



Jon W
03-11-2010, 12:33 PM
I'm having a problem with $_COOKIE's on my site not working correctly. It seems as if the cookie is being set but at the same time is not being set as a global cookie which should happen. All cookies should be global. The use this cookie is to hold the chat color that a user is using. This is set by a ajax post request, you basically select a color from a color picker and on click it send that color via post inside of the $_POST['c'] array. After that it is then a met by a associative array that hold all of the colors:



$colors = array(1 => '#f1f1f1', 2 => '#ff593f', 3 => '#A51792',
4 => '#4E9258', 5 => '#2B65EC', 6 => '#DE954B',
7 => '#36b3e1', 8 => '#FD13DE', 9 => '#6eb361');

$num = $_POST['c'];


Then is later used inside of the setcookie(). Its odd, though because it seems to be setting it on the chatsystem.php page but when I go to echo or print it out onto the page where the chat system actually set, I get nothing for a value. I had this working before with $_SESSION but for this chat system I'm going to need to use cookies. So without any more delay I'll provide you guys with some code and see if you guys can figure out my mess up.



//Change your chat color.
$colors = array(1 => '#f1f1f1', 2 => '#ff593f', 3 => '#A51792',
4 => '#4E9258', 5 => '#2B65EC', 6 => '#DE954B',
7 => '#36b3e1', 8 => '#FD13DE', 9 => '#6eb361');

$num = $_POST['c'];

if($_POST['c'] && $_POST['c'] <= 9) {
setcookie('color',$colors[$num],time()+172800);
}


I should also say that I turned on ini_set('display_errors', E_ALL); and I found no errors being reported.

Thanks for any help I can get on this.

Jon W
03-11-2010, 12:52 PM
Okay so a little bit of a update. I found if I set the path works. Though I had trouble with it switching colors so I went a head and did this and this worked fine...



if($_POST['c'] && $_POST['c'] <= 9) {
setcookie('color','',time()-172800,"");
setcookie('color',$colors[$num],time()+172800,"/");
}


My question is, is this the way you would of done it? lol

Fou-Lu
03-11-2010, 08:18 PM
You shouldn't need to destroy a cookie in order to set a new one, it should just overwrite the original value. Now, if you were to set a cookie and immediately check if _COOKIE exists, then it should be null; setcookie doesn't stick until the next load of a page that can access it.

Path itself should be set within the cookie. But this depends on what you're doing with it. Using / will let you use it at a domain level, which IMO is the most handy way of using them. By default, its the current directory and any sub directories, so if you're cookie is being set at you're root directory level, then it should be accessable to all of you're scripts.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum