Simple example of using sessions in PHP. Quick and Dirty reference guide.

The basics

Sessions are locally stored variables or data. By local, I mean on the server. This data is then referenced by the webserver. Your end user will have a cookie with a session identifier. this is how your web server knows what data belongs to what user.

There are some security flaws here that can enable a remote attacker to snatch your session and gain information. However this isn’t covered here and is mostly quite difficult to do and not widely used.

Lets say you had a user on your website and they just told you their name. Lets say you now want every other page on your site to know their name?

This is how you would do it.

 

The code

First we need to start the PHP session. This must be declared before we output anything to the user, So put this at the top of your page:

1
session_start(); // Lets start the session

Now, To put some information into the session under the variable name of “name”.

1
$_SESSION['name'] = "John"; // Session "NAME" now has a value of John.

Want to retrieve this data and display to the user?

1
2
$name = $_SESSION['name'];
echo "Hello $name , Welcome to my webpage";

Comments are closed.