0
votes

I'm new to PHP and I am building a simple login form. I want to give users the option to check a box with the option "Stay Logged In". I'm using a cookie array to make this happen.

When the user hits logout, I'm using $_COOKIE = array() to remove the variables stored for this user. However, all of the documentation I've reviewed recommends using setcookie() and setting an expiration date to the past.

https://www.w3schools.com/php/php_cookies.asp

How to delete/unset a cookie on php?

https://php.net/manual/en/features.cookies.php

Why is the setcookie() method superior? I've noticed when clearing user information with setcookie(), the changes don't take affect until after a page refresh.

1

1 Answers

2
votes

Why is the setcookie() method superior?

It's not superior, it's the only method that actually works.

Changing $_COOKIE changes it only for the current request. On the next request, the array will be filled again with all the cookies the users browser sends. You have to inform the browser about the change, and the only way to do this is to use setcookie.

You can, if you want, do both, setcookie and change $_COOKIE, to make sure, you don't use the old (soon-to-be-gone) value later in your script.