Google search

Basic and advanced computer skills like Excel with macros, How to speed up your PC, C, CPP, Java programming, HTML, JavaScript, PHP, Wordpress, all web tools, Android tutorials, MySQL Tutorials, WAMP server installation. etc.

Login with session in php

The following example shows use of Login authentication with session variables.

Before we create programs, let's first create a table called "users" in your database with following screen image.
[both usernm and password field type set to "varchar"]




1. Create Login2.php with following code in it.
<?php  
session_start();
?>  
 
<html>  
 <title>Login</title>  
</head>  
<body>  
  <h1> Login here </h1>
<form name="form" method="post" action="login2.php">  
<input class="form-control" placeholder="User name" name="email" type="text" autofocus>   <br>
<input class="form-control" placeholder="Password" name="pass" type="password" value="">  <br>
                 
<input  type="submit" value="login" name="login" >  
</form>  
</body>  
</html>  

<?php  
$con = mysqli_connect('localhost','root','','mars_db');
  
if(isset($_POST['login']))  
{  
    $user_email=$_POST['email'];  
    $user_pass=$_POST['pass'];  
  
$check_user="select * from users WHERE usernm='$user_email' AND password='$user_pass'";  
  
    $run=mysqli_query($con,$check_user);  
      if(mysqli_num_rows($run))  
    {  
  echo "<script>window.open('welcome.php','_self')</script>";  
  
        $_SESSION['email']=$user_email;
      }  
    else  
    {  
      echo "<script>alert('Email or password is incorrect!')</script>";  
    }  
}  
?> 

 2. The output looks like following image.






3. Now create a file called "welcome.php" with following code in it.
<?php  
session_start();  
  if(!$_SESSION['email'])  
{  
header("Location: login2.php");
}  
  
?>  
 
<html>  
<head>  
  
    <title>  
        Registration  
    </title>  
</head>  
  
<body bgcolor="green" text="white">  
<h1>Welcome</h1>
<?php  
echo $_SESSION['email'];  
?>  
 
<h1><a href="logout2.php">Logout here</a> </h1>  
</body>  
</html>  

4. Output of the above code would produce the following screen shot.







5. Now create a file called "logout2.php" with following code in it.
<?php  
session_start();
session_destroy();  
header("Location: login2.php");
?>

No comments:

Post a Comment