- Part 1: Server Output
- Part 2: $_SERVER
- Part 3: $_GET, $_PUT, and $_REQUEST
- Part 4: $_COOKIE
- Part 5: $_SESSION
The $_SESSION superglobal can be thought of as “long-term cookie.” When the function setcookie() is used, it creates a cookie on the client and sets how long it should live. With sessions, the cookie remains until it is either destroyed or the client closes their browser.
The function session_start() begins a new session. Once created, key-value pairs can be saved into the $_SESSION variable. It will maintain these until the variable itself is destroyed.
As a longer-term cookie, the session_start() variable must also follow the same restrictions as other cookies: it should be called or part of code before the main section of the page in which it is used so that it can be sent in the header.
Like any other variable, a session can be ended through unsetting its key-value pairs. Using the unset() function will erase the session’s particular key-value pair.
Cookies or Sessions?
In nearly all situations, using a session is more secure than any short-term cookie solution. For the client, the session is generated string of letters and numbers. For the server, however, it is, depending on settings, a file or some reserved memory that contains all the key-values pairs saved to it. In order to get at the data, an attacker would need access to the server itself.