Handling Sessions in PH
A session is a small piece of information which is stored at
server [Link] session is used to store and pass information
from one page to another temporarily(until user close the
website)
A session technique is widely used in shopping websites where
we need to store and pass cart information [Link] name,
product code, product name, product price etc from one page to
another
In simple words, A session is a way to store information (in
variables) to be used across multiple pages
Start a PHP session
session_start() function is used to start the [Link]
starts a new or resumes existing session
Example:
session_start();
Note : The session-start() function must be the very rst thing in your
document.
To get and set session variables :
$_SESSION is an associative array that contains all session
[Link] it is used to set and get session variable values
Example: To set session variable or store information in
session variable
$_SESSION["name"] = "NETAJI";
.
fi
.
Example: To get session variable or get information from
session variable
echo $_SESSION["name"];
Example1
A simple example to understand working with sessions in PHP. In
t h i s , t h e re a re t wo P H P p ro g r a m s , r s t p ro g r a m
([Link]) is to create session variables and store
information. And the second program ([Link])
is to get the information from the session variable
Example: "[Link]"
<?php
// to start the session
session_start();
?>
<html>
<body>
<?php
// To create session variable called "name"
$_SESSION["name"] = "NETAJI";
?>
<a href="[Link]">Click Here to Visit Next
Page</a>
</body>
</html>
Example: "[Link]"
<?php
// to start the session
session_start();
:
fi
.
?>
<html>
<body>
<?php
// to get the infromation from session variable
echo "Website Name is: ".$_SESSION["name"];
?>
</body>
</html>
Output
After clicking on the above Hyperlink
Example2
:
In this example, reading input from a text eld and storing it in a
session variable after which another page reads the value of the
session variable
Example: "[Link]"
<?php
// To start the session
session_start();
?>
<html>
<head>
<title>Session example</title>
</head>
<body>
<form name="form1" method="post">
Name : <input name="uname" type="text">
<br/><br/>
<input type="submit" name="Submit" value="SUBMIT">
</form>
<?php
if(isset($_POST['Submit']))
{
$_SESSION["name"] = $_POST["uname"];
header('Location: [Link]');
}
?>
</body>
</html>
Example: "[Link]"
<?php
// To start the session
session_start();
?>
.
fi
<html>
<head>
<title>Welcome </title>
</head>
<body>
<br/>
<?php
echo "Welcome : ".$_SESSION['name'];
?>
</body>
</html>
Output
Once the SUBMIT button has been pressed
:
Destroying Session :
session_destroy() function is used to destroy all
session variables completely
Example:
session_destroy();
.