PHP as a Programming language and development toolkit has a lot of advanced and easy to work with features for both new and existing programmers. PHP has built-in powerful session and cookie handling features. You can easily use sessions and cookies with core PHP functions without much effort. Use sessions for short-term state saving and cookies to store long-term data in the user’s browser.
PHP Sessions
PHP Sessions The PHP session handling is straightforward. You need to know 4 main things. First, use the start() and destroy() functions. Second, learn how to set sessions. Third, learn how to access session variables after you store them.
Session Start and Session Destroy
The first and most important rule for handling PHP Sessions is “start the sessions manually unless the server is configured to auto-start them”. Most servers don’t have this setup, unless a developer changes it. This is not recommended due to added overhead and processing. The standard way to run sessions is to use the session_start() function, which is a simple and basic function call without any parameters. This informs PHP to start the session handling system. Place this at the top of every page where you want sessions to run or include it in a require/include file at the top of all pages for global activation.
Below is a little example code:
<?php
session_start();
?>
Add this to the top of every page where you want to allow sessions. For convenience, set it in a config file or include file and require it on every page of the site. If you’re using a framework, turn it on as a configuration option.
To log out, simply call the session_destroy() function.
session_start(); // Starts the session handling
session_destroy(); // Destroys all saved sessions
header('Location: index.php'); // Redirects to the homepage (assuming index.php is the homepage)
In this example, we start the session engine, destroy any set session variables, and redirect to the homepage after logging out. Place the session_start() function at the very top of your page. It must be the first line. If there is even one character of code or one line of white space before this, it will register as headers already sent, and the session will not start, likely resulting in an error.
Saving Sessions
Saving a session variable is also very simple. It takes 1 line of programming to successfully save a session variable.
<?php
$_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.
<?php
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:
<?php
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.
<?php
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:
<?php
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:
<?php
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.
The PHP manual can be found here.
Other Archived random blog posts can be found here.