In this article we will discuss what are
Sessions and how to work with sessions in PHP. This tutorial will guide
you through setting up a session and also tell you how to unregister a
session.
PHP Sessions
Overview: In this article we will discuss what are Sessions and how to work with sessions in PHP.
Imagine
that you have some data about a particluar user that you need on all of
the pages, woudn't it be great if you could store that info in a
variable and access it from any page, Sessions exactly do that.
Using sessions you could hold data about particluar user and access
that info on all the pages as long as the user is active on the site.
* Each session holds different values for different user.
* Sessions automatically die when the users session is over or he closes his browser.
PHP's session-handling features, was first introduced in the 4.0
release, Sessions are native and thus require no additional packages.
To work with Sessions we will be using session_start() and session_register() functions, its important that you add sesions_start to every page where you would like to use sessions.
I will explain you the conecpt with an example.
// create a new session
session_start();
// register a session-variable
session_register("color"); //we have created a session with name color
$color = "blue"; //assigning some value to our session
?>
Okay now we have created a session with name color and assigned it as blue, now in our second programme (session2.php) we access the value of our session color
session2.php
session_start();
echo "The value stored in your session: " $color; //retriving value from the session
?>
To delete a session variable we use the function session_unregister() so to delete our session color we would use the code
session_unregister(color);
?>
|