PHP Sessions
Sessions are special kind of variables which are used to store data into that needs to be ‘remembered’ and needs to be accessed from different files. For example: you need to store the username of the logged in user on your website. Once the username is stored into a variable, you do not want the username to be lost when the user reloads the page or goes to another page of your website. Therefore, you can use special variables: sessions. All sessions belong to one array of sessions ( they are sub-variables of the array ): $_SESSION. To create a session variable, you simply create a sub-variable of this array. E.g.:
$_SESSION[‘username’] = “Admin”;
You can access any of your session variables on any page of your website. However, there’s one requirement that has to be fulfilled: you need to activate sessions before you can use them. This can be done by calling the function session_start. This must be done before outputting anything graphical ( e.g. HTML / Text ). For example:
<?php session_start(); $_SESSION[‘username’] = “Admin”; //… here goes the rest of your webpage … echo “Hi there, “.$_SESSION[‘username’].”!”; ?>
Calling the function at the beginning of the file is always good.
Example of usage:
create_session.php
<?php session_start(); $_SESSION[‘username’] = “Admin”; ?>
Note: You have to run this file to make it create the session.
use_session.php
<?php
session_start();
if(isset($_SESSION[‘username’]) && !empty($_SESSION[‘username’])) {
$username = $_SESSION[‘username’];
}else{
$username = “guest”;
}
if($username == “Admin”)) {
echo “Welcome back, Admin!”;
}else{
echo “You’re not allowed to be here, “.$username.”!”;
}
?>