سؤال

I have set up a simple login page on http://mywebsite.com/control. When you login, it places a cookie called user on your computer. To set the cookie I simply use:

setcookie("user", $_POST['IGN']);

When I am on the directory /control, it works fine. For example, if I use the code:

echo $_Cookie['user'];

it echos out the cookie information. However, if I do this on any page that is not in the /control directory, it says:

Notice: Undefined index: user in /var/www/other/vars.php on line 16

Line 16 is where it echos. This is an image of the cookie information in Chrome:

enter image description here

هل كانت مفيدة؟

المحلول

You should use:

setcookie("user", $_POST['IGN'],0,'/');

if you want cookie to be visible in the whole domain

You should also use:

echo $_COOKIE['user'];

with capital letters

You should also read more about setting cookies at http://www.php.net/manual/en/function.setcookie.php - by default cookies are set only for directory where you set cookie. That's why you need to add as 4th parameter '/'

نصائح أخرى

It does that because you are not setting the path parameter when you set your cookie, and by default, PHP will take the current directoy you're in.

Try this.

setcookie("cookiename", "value", time()+3600, "/", "mywebsite.com");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top