开发者

Why is this combined usage of cookies and sessions working? Confused

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['u开发者_StackOverflow社区ser_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.


Only the session id is stored in a cookie; that's used to link multiple requests from the same user as one session. Upon sending a request from the client, the session id from the cookie is sent in the request, and the server uses that id to identify the client and retrieve the contents of the session. The actual variables stored in the session are stored on the server.


Cookies and sessions are two entirely different systems.

PHP's sessions does use a unique session ID in a cookie to track sessions, but any other cookies set will not affect it, and sessions are not stored in cookies (they're stored server side in memory or files depending on your php config).

session_start() creates that unique session ID and stores it in the cookie.

$_SESSION['user_id'] = 'string' sets the variable on the server side.

On next page refresh it grabs the session from the unique session ID and populates the $_SESSION variable with everything set in the other requests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜