Reputation: 911
I'm learning about superglobal variables.I'm getting undefined index error while accessing the created cookie using $_COOKIE
I've created a cookie using setcookie('name','saravana') and i accessed it immediately using $_COOKIE['name'] (inside the if statement) .... it didn't work when I Accessed it inside "if" but when i Accessed it outside the "if" it worked .... Then After the cookie gets created in my browser ,I can access the cookie inside the if statement without any problem ...Then I deleted the cookie from my browser and tried to access the cookie from inside the 'if' it again showed undefined index error. The Question I'm Having is does the cookie get created after interpreting the line setcookie() or it gets created after completing the 'if' statement.. If it gets created by the time of interpreting setcookie() then why I can't access the cookie with if statement. Thanks in advance.Sorry for bad grammer!!
//Creating cookie for the first time
<?php
if (setcookie("name","saravana")){
echo "cookie is created".$_COOKIE['name'];
//undefined index error
}
//echo $_COOKIE['name']
//works fine.How??
?>
Ouput of 1st code: Notice: Undefined index: name in C:\xampp\htdocs\Test\cookies.php on line 3 cookie is created
Upvotes: 0
Views: 626
Reputation: 484
After setting up cookie will be available in next request (see documentation for setcookie() function). You can't access the cookie right after setting it up.
Upvotes: 1