Search code examples
phpcookiessetcookie

unsetting cookie getting Undefined index


test.php

<?php
setcookie('username', 'mary', time()+1000);


setcookie('username', 'mary', time()-1000);


 ?>

view.php

<?php
echo $_COOKIE['username'];


?>

Error I am getting after unsetting cookie

Notice: Undefined index: username in C:\Users\joe\Documents\Discrete Math\xampp\htdocs\view.php on line 3


Solution

  • You're defining a cookie only to immediately unset it. Calling setcookie on username with a negative time is essentially calling unset($_COOKIE['username']) (therefore, the index in the cookie superglobal is no longer, and thus the undefined error).

    I call this expected behavior.