PHP Sessions Example



PHP Sessions Example

Previous PHP tutorial we learnt about session how to create a session, retrieve session and destroy session. In this PHP tutorial we will learn more about session with php form example to create a session and retrieve and destroy session.

PHP Session Exmaple

First, design php  form with one textbox control with three buttons, one for create session second for retrieve session and last for destroy session. Here, we first create session using session button. When the create session button clicked then $_SESSION[“sname”] session created with the value of textbox control. after creating session we retrieve the $_SESSION[“sname”] value using view session button. finally we destroy all session using session_destroy() function with click of destroy button. After destroying we try to get $_SESSION[“sname”] values it shows error message like “All Sessions Destroyed !!”.

PHP form for session example like :

<?php
session_start();
?>
<html>
<head>
<title>PHP Session Example</title>
</head>
<body>

<FORM method="POST">

Enter Name : <input type="text" name="name"> <br/> 
<br/>
<input type="submit" name="Submit1" value="Session">
<input type="submit" name="Submit2" value="View Seesion">
<input type="submit" name="Submit3" value="Destroy Session">
</FORM>

<?php
if(isset($_POST['Submit1']))
{ 
$_SESSION["sname"]=$_POST["name"];
}

if(isset($_POST['Submit2']))
{ 
if(isset($_SESSION["sname"]))
{
echo "The Session Value = " . $_SESSION["sname"];
}
else
{
echo "All Sessions Destoyed !!";
}
}
if(isset($_POST['Submit3']))
{ 
session_destroy();
}
?>

</body>
</html>

The PHP session example output is :

PHP Sessions Example
PHP Sessions Example : Create, Retrieve and Destroy Session in PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *