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);
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.
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.
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.
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() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With