Dealing with Sessions and Cookies in PHP

PHP has powerful Session and Cookie handling features built in. You can have full use of sessions and cookies with built in core PHP functions, without a great deal of work. Sessions are generally used for short term state saving, while cookies are meant to store long term data in a users browser.

PHP Sessions

PHP session handling is very simple. There are 4 primary things you need to know. The first thing is the PHP start() and destroy()
functions. The second thing is how to set sessions. The third thing you should know, is how to access the session variables after
you have stored them.

Session Start and Session Destroy

The first and most important rule in dealing with PHP Sessions is “Sessions have to be started, unless the server is configured to auto-
start them”. Most of the the time the server PHP Settings are not setup like this, unless a developer has changed them. This is
generally not recommended. This adds extra overhead and processing, and is not generally recommended. So the standard way to run
sessions is using session_start() function. It’s a very basic function call, which doesn’t require any parameters. This just tells
PHP to start the session handling system. It can be used at the top of every page that your wanting sessions to run in. It can
also be entered into a require/include file at the top of all of the pages, and then it’s activated globally.

Below is a little example code:


session_start();
?>

You simply put that at the top of every page that you want to allow sessions. It’s easier if you set this in a config file, or include file and just require that on every page of the site. This is assuming your doing a standard basic procedural site. If your using a framework of some kind, then generally this option is easily turned on within the framework of your choice as a configuration option.

The standard logout functionality is also very easy. You simply call the session_destroy() function.


session_start(); // Starts initial session handling
session_destroy(); // Destroys all currently saved sessions
header('Location: index.php'); // Redirects back to homepage, assuming index.php is the homepage.
?>

In this example, we are starting the session engine (so PHP has access to the destroy function) then we are destroying any Session
variables that have currently be set. Generally code like this is used on a logout page, which almost always redirects to some
location. So I have included a line of code to set a header in PHP to tell the browser to take them to index.php. That url can
be changed to whatever you want it to redirect them too.

That is all that is required to totally destroy a session and log someone out.

There is one more detail to keep in mind about session_start(). Make sure you always include it at the VERY top of your page.
It needs to be the very first line. If you even have 1 character of code before this, or one line of white space..then it is
going to register as headers already sent. In this case, it will not start the session, and generally will throw an error as well.

Saving Sessions

Saving a session variable is also very simple. It takes 1 line of programming to successfully save a session variable.


$_SESSION['variable'] = value;
?>

This simply sets a session named “variable” to a value of “variable”. The name and value can be changed to whatever you want, even
another variable. These variables can be set to strings, numbers, or arrays. Pretty much any standard variable can be placed within a
session.

Below is a basic example of how you would go about setting up session information when someone logs in. This code is not
optimize or geared for a production environment. It was also not tested.


session_start();
$sql = "SELECT * FROM user_information WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
}
?>

That would simply check to see if the person is logged in (assuming username/password were from a from, have been validated, and
were sanitized). From this point you could access the same sessions you have just saved. Let’s assume you want to print their
first name and last name on a welcome page. You could do something like the example below:


echo 'Welcome: ' . $_SESSION['first_name'] . ' ' . $_SESSION['last_name'];
?>

That would print out their first and last name. This assumes you have set session_start() somewhere in your script.

Using Cookies for extended State Saving

So let’s assume you don’t want the sessions to get destroyed every single time someone closes their browser. Well that is what happens.
When they close their browser the server destroys the sessions and forget they even exist. Using a variety of session options people can
avoid this..but it takes additional resources that aren’t needed. Or you could simple save the sessions into a database (Which I don’t do very
often, but may blog about some time in the future). So what do you do? You use a cookie to allow the sessions to be re-set every time they come to the site.

So the general idea is simple. When you create the session you save a cookie of just the user id.


session_start();
$sql = "SELECT * FROM user_information WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
setcookie('user_id', $row['user_id']); // Set a cookie for the user id.
}
?>

That is all you need to do to set a cookie. One extra line of code. Now in the situation where they return to the site it’s time to retrieve it.
In general you would need a lot more. Like you would want to check if they are authorized to view certain pages or whatever else, but that is outside
the scope of this post. So let’s assume you just want to check something when they come to the site. IF they have a session already, then great. We need
to do nothing. IF they don’t then we can see if they have a cookie and do something with it. So here is what you could do:


session_start();
// If there is no session then let's see if we can get one from a cookie.
if ($_SESSION['user_id'] == '') {
// See if the cookie is set
if ($_COOKIE['user_id'] != '') {
$sql = "SELECT * FROM user_information WHERE user_id = '" . mysql_real_escape_string($_COOKIE['user_id']) . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
setcookie('user_id', $row['user_id']); // Reset the cookie just to be safe.
}
?>

That’s it. It will check to see if they have a cookie, if they do it’ll rebuild the session data (exactly as if they had logged in) and that’s it.

Session ID

Just recently I ran across another nice PHP function that deals with obtaining the ID of the current session.  This has a few good uses..for example, generally if your using a Shopping cart it’s based on session.
You will generally use the session to store the cart, then retrieve the session when your done. I use to use extensive code to get the session ID, until I found this function.  Below is a simple example:


session_start();

$session_id = session_id();

echo $session_id; // Outputs the session ID
?>

Disclaimer

Disclaimer: None of this code was tested thoroughly, and is not intended for a production environment.  Use at your own risk, I take no liability from issues/problems that arise from using this same code.

Comment with your Facebook Account


Comment Without Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *