Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 594
Osman Avatar asked Aug 07 '12 07:08

Osman


People also ask

How do you Fix an Undefined index?

Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php. ini file.

How do you check if a cookie is set?

Right-click and click on Inspect Element to open the developer console. Go to the Storage tab. Expand the Cookies menu and select the website to check cookies. On the right side of the console, you will see the cookies that have been set on the website.

How to prevent Undefined index PHP?

The error can be avoided by using the isset() function. This function will check whether the index variables are assigned a value or not, before using them.

How to check Undefined index in PHP?

To check if a variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars() .


1 Answers

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.

like image 161
Jerska Avatar answered Oct 19 '22 23:10

Jerska