Wednesday, February 7, 2018

PHP Login Form using Session

In this post you will learn login form source code using session without storing details in the database. In our next post you will see login form using session storing details in database.

Step 1: First create login page named as index.php

<?php>
session_start();    // Session start
if(isset($_POST['check']))    // Check form submit with IF Isset function
{
$username="lucky";    // set variable value
$password="123";        // set variable value
if($_POST['username']==$username && $_POST['password']==$password)   // Check Given user name, password and Variable user name password are same
{
$_SESSION['username']=$username;    // set session from given user name
header('location:mainpage.php');
}
else
{
$err="Authentication Failed Try again!";
}
}
?>
 <html>
<head>
<title>Main Page</title>
</head>
<body>
<Center>
<?php if(isset($err)){ echo $err; } ?>      <!-- Print Error -->

<form method="POST" name="loginauth" target="_self">
 User Name: <input name="username" size="30" type="text" />
<br/><br/>
Pass Word: <input name="password" size="20" type="password" />
<br/><br/>
<input name="check" type="submit" value="Authenticate" />
 </form>
</center>
</body>
</html>

Step 2: Now create mainpage.php

<?php
session_start();    //session start
if(!isset($_SESSION['username']))     //if session not found redirect to homepage
{
header('location:index.php');
}
echo "Welcome &nbsp;";
echo $_SESSION['username'];      //retrieved using session
?>
 <html>
<head>
</head>
<body>
<center>
<h2>Welcome to Main page</h2>
<a href="logout.php">logout</a>
</center>
</body>
</html>

Step 3: Now create LOGOUT.PHP page for destroy the session

<?php
session_start();
if(!isset($_SESSION['username']))     //if session not found redirect to homepage
{
header('location:index.php');
}
unset($_SESSION['username']);       // Session Found Unset the variable values
session_destroy();                  // Destroy the session
header('location:index.php');
?>


OUTPUT:



No comments:

Post a Comment