Friday 12 February 2016

Login form with session

Code: 

index.php

<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<center><h1>Login</h1>
<?php
if(isset($_POST['submit']))
{
    $conn=mysqli_connect("localhost","root","","login");
    $user=$_POST['username'];
    $pass=$_POST['password'];
    $qu="SELECT * FROM registerform WHERE username='{$user}' AND password='{$pass}'";
    $result=mysqli_query($conn,$qu);
    $count=mysqli_num_rows($result);
        if($count == 1)
        {
            $_SESSION['username']=$user;
            echo "<script>document.location.href='display.php'</script>";
        }
        else
        {
            echo "<script>alert('Invalid Username or Password')</script>";
        }
}
?>
<form name="signin" method="post" action="index.php">
Username: <input type="text" name="username"/>
Password: <input type="password" name="password"/>
<input type="submit" value="Login" name="submit"/>
</center>
</body>
</html>




display.php

<?php session_start(); ?>
<?php
    if(isset($_SESSION['username'])){
   
    }else{
   
        echo "<script>alert('Please Login')</script>";
        echo "<script>document.location.href='index.php'</script>";
    }
?>
<!DOCTYPE html>
<html>
<body>
<center>
<?php
    echo "<h1>Welecome to Home<br/></h1>";
    echo $_SESSION['username']." successfully logged in";   
?>
<center><br/>
<a href="logout.php">Logout</a>
</center>
</body>


Logout.php

<?php session_start(); ?>
<?php
        session_destroy();
        echo "<script>document.location.href='index.php'</script>";       
?>

Output:

No comments:

Post a Comment