I’m confused as to why this is working;
setcookie("user", $user_id, time()+604800);
session_start();
$_SESSION['user_id'] = "string";
Even though setcookie() contains no reference to $_SESSION['user_id'], when I echo $_SESSION['user_id'] from another page with the code:
session_start();
echo $_SESSION['user_id'];
It prints string.
I was under the impression that setcookie() had to reference a $_SESSION key in order for it to be called from any page?
Perhaps I’m well off base, but I just want to make sure I understand why this is working before I implement it, as I’d rather it not fault because of incorrect usage.
Any help, comments, advice and explanations will be appreciated!
setcookie() sends a generic cookie to the browser while session_start() initializes a session and sends a session cookie to the browser. With
setcookie(), you can send whatever you want in the cookie, such as the user’s username and password to be remembered between visits, or any arbitrary text. Note that all of this is stored right in the cookie itself and can be manipulated by the user and therefore should not be trusted.With
session_start(), on the other hand, everything is handled server-side. The only thing sent in the cookie is the session identifier. Session data cannot be directly manipulated by the browser. PHP also handles collision prevention, data storage (which by default is a plain text file viewable only by root and stored in /tmp) and expiration (even if the cookie is manipulated by the browser.)Essentially, even though these functions are similar in that they both send a cookie to the browser, they both serve completely different purposes.