简体   繁体   中英

Why session_start is needed when using session?

为什么我可以在不使用$_SESSION之前需要session_start()而无需任何准备的情况下使用setcookie ?我认为它们的工作原理是相似的。

Because setcookie() defines a cookie to be sent along with the rest of the HTTP headers . That's a completely different thing than what session_start() does, eg creating a session or resuming the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

The first just adds something to the header and sends it to the browser, while the other gets the Session ID from $_COOKIEs or $_GET or $_POST and then tries finding the session file in the session_save_path and when found unserializing the values of it into $_SESSION and if not, create a new session, probably using setcookie in the process to set the Session Id.

See the chapter on Sessions in the PHP Manual.


Edit Like @Felix correctly points out below, the session is not necessarily saved in a file. It's not that important though, because the argument stays the same: session_start will find and (re-) initialize your session data, while setcookie just does what the name implies.

For explanation see the reply before mine. If you just don't want to call the start_session() function have a look at this setting in the php.ini: session.auto_start

The session data is not necessarily stored in a file as Gordon says. With session_set_save_handler() you can define your own backend that should store the values, eg in a database.

All this data retrieving is handled with session_start() . This way you can easily change you backend without breaking your application.

Note: This is only one reason for session_start() , and again it does lot more then just setting cookies.

The session data is not necessarily stored in a file as Gordon says. With session_set_save_handler() you can define your own back end that should store the values, eg in a database.

All this data retrieving is handled with session_start() . This way you can easily change you back end without breaking your application.

Note: This is only one reason for session_start() , and again it does lot more then just setting cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM