PHP Programing language

Session in PHP
Previous Home Next
adplus-dvertising

Session

Session is the different to store variable information/data which can be later used. The information/data stored by session variable is visible to multiple pages or visible to all pages of the web application.

Session creates file in temporary directory on server to store information. The session start with session_start() function before any HTML tags.

Start a PHP Session

A session is started with the session_start() function. Session variables are set with the PHP global variable i.e. $_SESSION. The session_start() function must be start before any HTML tags.

Example:

<?php
// Session start
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favfruit"] = "Mango";
$_SESSION["favseason"] = "Rainy";
echo "Session variables are set.";
?>
</body>
</html>

Output:

Session variables are set.

Get PHP Session Variable Values

Example:

<?php
session_start();
?>
<html>
<body>
<?php
echo "Favorite Fruit is " . $_SESSION["favfruit"] . ".<br>";
echo "Favorite Season is " . $_SESSION["favseason"] . ".";
?>
</body>
</html>

Output:

Favorite Fruit is Mango.
Favorite Season is Rainy.

Destroy a PHP Session

To remove all global session variables and destroy the session, you can use session_unset() and session_destroy().

Example:

<?php
session_start();
?>
<html>
<body>
<?php
session_unset(); 
session_destroy();
echo "All session variables are now removed, and the session is destroyed." 
?>
</body>
</html>

Output:

All session variables are now removed, and the session is destroyed.

Previous Home Next