简体   繁体   中英

Notice: Undefined index: when calling a cookie that is set

So i have a cookies that i know is set properly (using firefox get page info) and I keep getting the error/ warning "Notice: Undefined index: ". I am accessing the cookie by using $_COOKIE['username']; and when I do if(isset($_COOKIE['username'])) the code does not run. However I can see the unexpired cookie in firefox get page info. Just for reference here is my set the cookie code : setcookie('username', $username, time()+3600*24);

You were probably defining the cookie in a php file that was in a different folder of your php file where you were calling your isset.

So adding '/' as the default folder of the cookie makes it availaible for the entire website.

Sometimes, you don't want this to happen, because you might want to have two cookies with the same name but different values depending on which folder you're in.

Example: A website with 2 languages, you could have $_COOKIE['language'] = 'en'; in the /en/ folder and have $_COOKIE['language'] = 'fr'; in the /fr/ folder.

So when you're setting a cookie without specifying its directory, you have to remember that it will only be available only for the files in the same folder or in subfolders.

$expire = time()+60*60*24*30;          
setcookie("MyName", "Khan", $expire,'/');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM