Server-Side PHP: Part 5: $_SESSION

Server-Side PHP


$_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.

Starting Sessions

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.

Ending Sessions

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.