A session is an essential technology in web development. At a basic level, a session is used to store information about one logged-in user at a time. For this tutorial, we'll be using PHP and analyzing sessions as they're used in that language.
When you log into a website and see information on a page unique to you (i.e., a profile page), a session is used. When you log out (assuming the webpage is secure), there is no way to view or edit your profile page without logging back in. Whenever you log in, the PHP starts a session unique to you. While you're logged in, you can view and sometimes edit information that is reserved only for people who are logged in, oftentimes working with information unique to the user. When you log out, the PHP will end the session.
Sessions are normally used alongside a database, the location where storage is kept within the web server. Using PHP, a programmer can, for example, receive input from a user (i.e., "enter your username and password"), compare them to what is inside their database (being careful to avoid SQL injections and other attacks), and, if correct, can start a session with information kept inside of the session variable (i.e., the username).
Sometimes when you log into a website, you'll see your name with some greeting ("Welcome back, John!"). In this tutorial, I'll walk you through the basic mechanics of how this works.
Let's take a look at how sessions are used in a login system:
When you get to the point in your code where you want a user to be logged in, be sure to add the following code:
<?php
session_start(); //begins session at this point in the code.
?>
You'll want to put this in the portion of your code dedicated to logging the user in (i.e., within an "if" statement). The following is an example within a class I made for a login project:
<?php
// $checkPassword sees if the password given for a specific username is true or not.
elseif($checkPassword == true)
{
$stmt = $this->connect()->prepare('SELECT * FROM user WHERE username = ? AND password = ?;');
//This is a SQL statement that grabs information from the database
// A couple of error handlers were placed here,
$user = $stmt->fetchAll(PDO::FETCH_ASSOC);
// This arranges the information received from the
// database into a usable array.
session_start();
// Starting at this point of the code, a
// session has begun.
$_SESSION["id"] = $user[0]["id"];
// This adds information to the session,
// specifically the user ID number received from
// the database.
$_SESSION["username"] = $user[0]["username"];
// This adds the username into the session.
$stmt = null;
}
?>
You should also know that, on any page using a session variable, you'll need to start the session before anything else (i.e., before any php or html code):
<?php // Put this on line 1 of your code for each page.
session_start(); // Begins session at this point in the code.
?>
Once a user is logged in, sessions can be used to display information unique to the user. Here's an example of how a session can be used to display a username on an index.php page:
<?php // Be sure to add this at the start of the code!
session_start();
// Some other code may appear here
if (isset($_SESSION["id"])){
// This checks the global variable $_SESSION and sees
// if "id" exists within the session and if the session
// is filled with data.
echo "<h1>Hello, <h1>";
// This is PHP's way of echoing HTML code, displaying "Hello, "
// on the webpage
echo $_SESSION["username"];
// This displays the contents of the $_SESSION variable, which,
// in this instance, is an array. This code displays the
// content of the associative array, showing what's connected
// to the "username" key (which is the username in this example).
}
?>
On webpages requiring a login, you'll often notice a "logout" button. For a user to be considered logged out, the session needs to end. Here is an example of some code you might write when logging the user out (i.e., if the user hits a "logout" button):
<?php
session_start();
// To use sessions, always start your code with this line
// of code (even if you're trying to end the session).
session_unset();
session_destroy();
// These two are used together to clear and end the session.
// The $_SESSION global variable no longer has anything inside
// of it.
header("location: ../index.php");
// This simply redirects the user back to the index.php page.
?>
Once the session has ended, the user is logged out and can no longer view information unique to him/her.
Sessions utilize cookies that are uniquely assigned to a specific browser. If a user clears their cookies while they're logged in, their session will end.
Hope this tutorial was helpful!
This YouTube video by Dani Krossing is where my knowledge and experience with sessions comes from. His walkthroughs are incredible and I can't recommend him enough. You'll have trouble with him if you're a more advanced programmer, he takes everything really slow. I'd recommend the entire walkthrough, but you can click here for the portion discussing sessions and how they're used.
This W3Schools page on Sessions is also helpful. W3Schools in unique because it has interactive examples you can use to better understand sessions. This isn't as comprehensive as the video above. This is a better resource for someone more experienced with programming who'd just like a quick answer. It's also good for beginners who want to learn more about sessions through trial and error. It's also a great resource for understanding basic syntax and layout, showing well-written examples of what your code should look like.
This php.net page is a more comprehensive list of several ways sessions can be used. I'd only recommend this to advanced programmers.
This TutorialRepublic page has the same concepts I wrote in my tutorial, just with different wording and examples. A different explanation may be helpful if what I wrote is confusing at all.