How to Create and Destroy sessions in PHP

Sessions are used in php for saving data which is used on several pages like in cpanel we need admin id on all pages to verify him and if the session destroy the user have to login again .
in this post i use a text box and two pages text box is to enter any value and then save that value in session and check on both pages that is this session exist? and if we destroy that session the value will not shown any more.


Start session:       session_start();
Assign value to session: $_SESSION['myname']= " $username";
Destroy session: session_unset();

Download Code


First page : index.php:


<!DOCTYPE html>
<html>
<head>
<title>Session is PHP</title>
</head>
<body>

<h2>To demonstrate the concept of session put a name in text box and check the session value by clicking buttons.</h2>
<h2><a href="usman.php">Second Page</a></h2>

<form action=" " method="POST">
<p><input type="text" name="username" placeholder="Type any name here..." required></p>
<p><input type="Submit" value="Check Session value"></p>
</form>

<form action=" " method="POST">
<p><input type="Submit" value="Distroy Session" name="dstroy"></p>
</form>
<?php
session_start();

if(isset($_POST['username'])){

$_SESSION['myname']=$_POST['username'];
echo "<br><h1>Session has a value= ".$_SESSION['myname']."</h1>";
}

if(isset($_SESSION['myname'])){
if(!isset($_POST['username']))
echo "<br><h1>Session has a value= ".$_SESSION['myname']."</h1>";
}

if(!isset($_SESSION['myname'])){
echo "<br><h1>Session not set...yet.!!</h1>";
}

if(isset($_POST['dstroy'])){
session_unset();
header("location:index1.php");
}

?>

<p>Check Session is user when user login in </p>
<p>Distroy session is used when user logout</p>
</body>

</html>



Second page: usman.php


<?php

session_start();
if(isset($_SESSION['myname'])){
 echo "<br><h1>Session has a value= ".$_SESSION['myname']."</h1>";
}

else{
echo "<br><h1>Session not set...yet.!!</h1>";
}


?>

<h2><a href="index1.php">First Page</a></h2>
<p>Check Session is user when user login in </p>

<p>Distroy session is used when user logout</p>


No comments

Powered by Blogger.