A session is a small piece of information which is stored at server side.And 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 e.g.user 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.
☞ session_start() function is used to start the session.It starts a new or resumes existing session.
Example:session_start();
☞ $_SESSION is an associative array that contains all session variables.And it is used to set and get session variable values.
Example: To set session variable or store information in session variable
$_SESSION["name"] = "StudyGlance";
Example: To get session variable or get information from session variable
echo $_SESSION["name"];
A simple example to understand working with sessions in PHP. In this, there are two PHP programs, first program (FirstPage.php) is to create session variables and store information. And the second program (SecondPage.php) is to get the information from the session variable.
<?php
// to start the session
session_start();
?>
<html>
<body>
<?php
// To create session variable called "name"
$_SESSION["name"] = "Study Glance";
?>
<a href="SecondPage.php">Click Here to Visit Next Page</a>
</body>
</html>
<?php
// to start the session
session_start();
?>
<html>
<body>
<?php
// to get the infromation from session variable
echo "Website Name is: ".$_SESSION["name"];
?>
</body>
</html>
In this example, reading input from a text field and storing it in a session variable after which another page reads the value of the session variable.
<?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: sessionPage2.php');
}
?>
</body>
</html>
<?php
// To start the session
session_start();
?>
<html>
<head>
<title>Welcome </title>
</head>
<body>
<br/>
<?php
echo "Welcome : ".$_SESSION['name'];
?>
</body>
</html>
☞ session_destroy() function is used to destroy all session variables completely.
Example:
session_destroy();