Ticker

6/recent/ticker-posts

PHP (Session)

SESSION IN PHP

INTRODUCTION
As like Cookies in PHP, sessions are also used to store data in a global variable (In session IDs).
But it is more secure as compare of cookies because it store data on server side rather than client side.


FEATURES OF SESSION
1. Global data: Any data store in sessions, can be share with multiple web pages.

2. Security: Session store data on server side, so its more secure as compare cookies.


3. Not visible: A user can see cookies but no one can see the session data.br /><





COMMON FUNCTION OF SESSION

$_SESSION: This function is used to create a session variable.

session_start(): This function is used to start a session in PHP.


session_unset(): This function is used to remove session variables.


session_destroy(): This function is used to destroy session.





PHP SESSION EXAMPLE
<?php
session_start();
$_SESSION['id']="101";
?>

Explanation: In the above code session_start() is using to start a session and $_SESSION creating a session and storing value '101' in sessio variable 'id'.



SESSION APPLICATION FOR LOGIN & LOGOUT

1. Create session a file with name "sess.php" and write the following code.
 <?php
session_start();
?>

<?php
if($_SESSION['id']==NULL)
{
 header('location:login.php');
}
?>




2. Create login file with name of login.php and write the following code.
<form method="post" action="data.php">

Enter Username:<input type="text" name="n"><br><br>
Enter Password:<input type="password" name="p"><br><br>
<input type="submit" name="sub" value="submit">

</form>


3. Create data.php file and write the following code
<?php
session_start();
?>

<?php
if(isset($_POST['sub']))
{
$name=$_POST['n'];
$pass=$_POST['p'];
$_SESSION['id']=session_id();
if($name=="aptech" && $pass=="123")
{
 echo "<script>location='home.php'</script>";
}
else
{
echo "<script>location='login.php'</script>";
}
}
?>


4. Create home.php file and write the following code.
<?php
include('sess.php');
?>

<html>
<marquee behavior="alternate">
<font size="7" color="#FF0000"> Welcome In My Home Page </font>
</marquee>

<body>
<a href="logout.php"> <h1 align="right">Logout </h1> </a>

</body>
</html>


5. Create Logout.php file and write the following code.
<?php
session_start();
session_unset();
session_destroy();
echo "<script>location='home.php'</script>";
?>


SESSION TIMEOUT() FUNCTION
This function is used to set a session expiry time and take argument in seconds.
Syntax: $timeout=60;

Example
<?php
session_start();
$timeout=60;
$_SESSION['id']="101";
?>
Program Explanation: In the above program session variable 'id' automatically expire just after 60 seconds.







Post a Comment

0 Comments