A session is object used to store information as long as your browser is open or until specify expiry time ends.
It's best used to store user login information to identify the user by login information and let them access restricted area of the web site.
It's also used to pass variables from one page to another or store user access information for visit statistics use.
To create session with php, you will have to create the session it self by typing session_start();
at beginning of your php code. It's important that the session creating statement must be the first line of you code other wise, you may get some ugly errors. This code registers user's session with server.
Now, we are going to create a user login session and store the values username and password:
<?php
session_start();
$_SESSION['userName'] ="MyUserName";
$_SESSION['password'] ="MyPassword";
?>
We created a session that retains username and password.
Just to show you what is stored, the following example check if a session exist and if so, prints the session values to the browser.
<?php
session_start();
if(isset($_SESSION['userName']))
{
print "Your session username: ".$_SESSION['userName']. "<br>";
print "Your session password: ".$_SESSION['password']."<br>";
}
else
{
print "Session does not exist";
}
?>
Execution Result:
Your session username: MyUserName
Your session password: MyPassword
To see more of utilization of session(), the following example checks if session exists and redirects the browser to different pages.
<?php
session_start();
if(isset($_SESSION['userName']))
{
header("Location: member.php");
}
else
{
header("Location: nonemember.php");
}
?>
Destroy session
session_destroy(); function destroy the session completely.
The following example is the code that you would normally put your php logout page.
It simply logs out the user by deleting the session and redirects the browser to the index page.
<?php
session_start();
session_unset();
session_destroy();
header("Location: index.php");
?>
|