Simple Login And Logout in PHP

Simple Login And Logout in PHP

We will learn the Simple Login and Logout System in PHP

We need 5 files -

dbconnect.php    // For Database Connection
index.php         // For displaying login form
login.php         // For login authentication (will check is user available )
logout.php       // After logout
welcome.php   // After Login

Note :- We have login table named 'login'


Now first we will create the database connection -

( In dbconnect.php)

session_start();      // this will start the session environmen
<?php

$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('DBNAME',$conn);

 ?>

Now we will create the login form -

( In index.php

<form method="post" name="login" id="login" action="login.php">
Username <input type="text" name="username" id="username"  /><br />
Password <input type="password" name="password"  /><br />
<input type="submit" name="submit" id="submit"  value="Login" />
</form>


 // This form will submit to login.php


Now we will check the database and provide authentication for login -

( In include('dbconnect.php');)


<?php
include('dbconnect.php');

if($_POST) {
    $username=mysql_real_escape_string($_POST['username']);
    $password=mysql_real_escape_string($_POST['password']);
    $query=mysql_query("SELECT id FROM `login` WHERE username='$username' and password='$password'");
    $count=mysql_num_rows($query);
    if($count!="")                                     // If login Authentication success
    {
     $_SESSION['username']=$username;
    header("Location:welcome.php");
    }
    else
    {
       header('Location:index.php');
    }
}


?>


Now we display the name of user  and provide a link to logout from welcome.php page

( In welcome.php)


<?php
include('dbconnect.php');
$user=$_SESSION['username'];
$query=mysql_query("SELECT username FROM `login` WHERE username='$user' ");
$row=mysql_fetch_array($query);
$login_username=$row['username'];
if(!isset($login_username))
{
header("Location:index.php");
}
?>

 Welcome  <h1><?php echo $login_username; ?></h1>
<p>This is your Welcome Page</p>
<br/>
 click here to <a href="logout.php">LogOut</a> !


Now when user clicks on logout then it will redirect to logout.php


( In logout.php)

<?php

include('dbconnect.php');      // We have to include it because session_start() is define here

if(session_destroy())
{
header("Location: index.php");
}


?>


No comments:

Post a Comment