In this login logout example in PHP & MySQL we will use three different files which are login.php,index.php and logout.php.
We need to add a table in our database named login_user which will have the following columns.
CREATE TABLE `login_user` ( `id` int(11) NOT NULL, `name` varchar(60) NOT NULL, `user_name` varchar(20) NOT NULL, `password` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
First, create a file named login.php and write the following code in it:
<?php
session_start();
$message="";
if(count($_POST)>0) {
include('connection.php');
$result = mysqli_query($con,"SELECT * FROM login_user WHERE user_name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
if(is_array($row)) {
$_SESSION["id"] = $row['id'];
$_SESSION["name"] = $row['name'];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"])) {
header("Location:index.php");
}
?>
<html>
<head>
<title>User Login</title>
</head>
<body>
<form name="frmUser" method="post" action="" align="center">
<div class="message"><?php if($message!="") { echo $message; } ?></div>
<h3 align="center">Enter Login Details</h3>
Username:<br>
<input type="text" name="user_name">
<br>
Password:<br>
<input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="Submit">
<input type="reset">
</form>
</body>
</html>
Now you need to write this code in your index.php file.
<?php session_start(); ?>
<head>
<title>User Login</title>
</head>
<body>
<?php
if($_SESSION["name"]) {
?>
Welcome <?php echo $_SESSION["name"]; ?>. Click here to <a href="logout.php" tite="Logout">Logout.
<?php
}else echo "<h1>Please login first .</h1>";
?>
</body>
</html>
Finally, we need to make a logout.php file to destroy the cookies and session we created in the login function.
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["name"]);
header("Location:login.php");
?>