PHP Sessions and Cookies
But that isn’t secure and isn’t nearly flexible enough for today’s web applications. Luckily, there’s a better way — and it’s right at your fingertips: sessions.
A session in PHP is a secure way to track a user from page to page. With a session, you can store information about users, such as their e-mail address, name, phone number, and whatever other details you have, and automatically fill in that information wherever it’s needed on the site.
For example, say that on login you load the user’s first name and e-mail address from your user database. You can store that information in a session, essentially hidden from the user, until you use it.
You use session variables as you would any other variables. Behind the scenes, sessions are stored in an array called $_SESSION. You store values just as you would with a named array in PHP. For example, you can keep track of an e-mail address and name like this:
$_SESSION['emailAddress'] = "email@example.com"; $_SESSION['firstName'] = "Steve";
You can also use sessions to keep track of information filled in on a web form without having to carry that information through the site in hidden form variables.
Sessions are passed in browser cookies, which are little extra bits of information that get sent to and from a web browser. The actual bits of information, or what those bits actually are, is up to you, the programmer.
For instance, you could send a cookie that contains the user’s name. The cookie could then be stored on the user’s computer and the next time she visits the site, the cookie would be sent to your program, which would then present a personalized greeting.
However, cookies are like any other data that you get from a user — the data from cookies needs to be sanitized because it can’t be trusted. In other words, once your program sends a cookie to a visitor’s browser, the visitor can edit or change that cookie to be anything he wants.
So if you (the web developer) are using the cookie to store a username, the visitor can change the username to whatever he wants and then send it back to your program.
The possibility of users editing their cookies is largely solved by simply using sessions. When a session cookie is created, it uses a hash value, which is a long string of characters. This means that even if users change the cookie value, in other words, if they change that hash, they aren’t really changing anything that you’re using in your program directly.
Instead, PHP handles the translation of that hash from the cookie on your behalf, and then you can get on with the business of using things in the $_SESSION array. The actual values that you store in the $_SESSION array are never seen by the user; they exist only on the server.
Of course, using sessions with cookies means that cookies need to be enabled in the user’s browser. If they aren’t, then the user can’t use the application.