PHP is one of the scripting language. In which session handling is one of the key thing mostly using in web application.
Suppose you build a website and allow to login everyone in website, You need to track user every step until they log out our system, Its called Session tracking.
Now the question is why we need to track the session, answer is very simple .HTTP state less protocol, When you refresh you page, Its lost every information, So this is the reason we need session handling.
To handle session in php we need to a global variable $_SESSION and session_start()
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Here above, we have set two session variable $_SESSION[favcolor] and $_SESSION[favanimal], Now we can access these variable thought the website and get corresponding value.
Another thing, if you want to destory session you need to use bellow methods.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
Setting up storing Sessions in a database
I was first introduced to storing Sessions in a database. So in order to store Session data in a database, were need a table.
Run the following SQL in your database to generate the table. Im using MySQL, but hopefully the following should be enough to get you started.
CREATE TABLE IF NOT EXISTS `sessions` (
`id` varchar(32) NOT NULL,
`access` int(10) unsigned DEFAULT NULL,
`data` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
1 Comment(s)