![php_logo_128]()
The
session_id() is one of the in built functions in PHP. Almost in all Framework's and CMS's it has been utilized to find the current session. In this tutorial we will see how to utilize this session_id() in small applications apart from Framework and CMS. Generally the session_id() will be used to track existence of same user across all the pages of PHP application. A Realtime example would be "tracking whether same user is navigating from one page to another". Lets see how this session_id() will be generated in a web application.
The below code shows the generation of session_id();
<?php
$a = session_id();
if(empty($a)) session_start();
echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>
The above code snippet shows how to set the session_id() in PHP. This session_id() will be generated whenever the page is calling
session_start() function.
Below steps shows you how to check the current session in multiple pages.
Step 1: Have one session library function in your application, say for eg:- session.php
<?php
session_start();
$sessionid = session_id();
if(empty($sessionid)){
header("Location:error.php");
}
?>
Step 2: Create one page in your application, eg:- error.php
<?php
echo "Error : Session is different ";
?>
Step 3: Create one page in your application, eg:- index1.php
<?php
include_once("session.php");
echo "This is first page having same session id";
?>
Step 4: Create one page in your application, eg:- index2.php
<?php
include_once("session.php");
echo "This is second page having same session id";
?>