PHP Sessions: What You Need to Know

Page content

PHP is one of the most revolutionary programming languages to ever hit the web, particularly because of its ability to keep “sessions”, which are small packages of data related to each user who enters a website. A normal PHP session begins when the function “session_start()” is called and ends in one of two ways. The typical way a session ends in PHP is when a user closes the browser. There are some scenarios, however, in which you might want to close the PHP session before this. The second way in which sessions end is when “session_destroy()” is called. After a session starts, you can allocate any data you want into the session, such as the browser IP, the username, and the hash of a user password. From the point the session begins, an array value called “$_SESSION” is declared. Only one session can be started per user. Once you call session_start(), you will not have to call it again in any other scripts. Choose wisely where you want to start a session!

A Seasoned Programmer’s Perspective of Sessions

If you are an experienced programmer, you already have had experience in making things similar to sessions. In PHP, sessions work much like how “struct” works in C++ or C or how tables work in LUA, if you are a scripter. The only problem with thinking of sessions as structs or tables is that they aren’t structs nor tables. The difference between a PHP session and both of these elements is that you cannot open multiple sessions like you can create multiple structs. It is best to think of sessions as a global LUA table rather than a simple C struct.

Sessions Broken Down for Novices

If you have no concept of what a table or a struct is, then you probably will not have understood the previous section. PHP sessions are simply arrays of data contained inside of an array variable. Think of it as a tree. As the tree grows, it has branches and leaves that multiply. Some branches grow on other bigger branches, and so forth. In a session, you can extend dimensions, which are levels at which data are stored. For example, an array with two dimensions in PHP would look like this:

“$categories[‘category1’][‘subcategory1’] = variable;”

“$categories[‘category1’][‘subcategory2’] = variable1;”

If you find this difficult, try playing around with examples of multidimensional arrays in PHP that you find around the Internet. You will probably find it better to get your hands dirty first and then understand the concept later.

Adding Session Data

In the $_SESSION variable, you can add data to it how you want. Let’s say you have a user who just logged in, and you want to store his username in the session array along with a hash of his password.

The way to do this is very simple (assuming you already pulled up the values from the database and stored the username in a variable called $name and the password hash in a variable called $pw):

“$_SESSION[‘uid’] = $name;”

“$_SESSION[‘pw’] = $pw;”