Osman
Osman

Reputation: 1771

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);

Upvotes: 5

Views: 9899

Answers (2)

user3400389
user3400389

Reputation: 367

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

Upvotes: 1

Jerska
Jerska

Reputation: 12002

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.

Upvotes: 6

Related Questions