PHP Login Logout examples with Session
Before going to example you need to learn what is PHP session()
In this login logout example in PHP we used 3 file:
- login.php
- index.php
- logout.php
login_user.sql
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;
login.php
$_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>
<?php
session_start();
?>
<html>
<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>
logout.php
login.php
<?php
session_start();
$message="";
if(count($_POST)>0)
{
$con = mysqli_connect('127.0.0.1:3306','root','','admin') or die('Unable To connect');
$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>
index.php
session_start();
?>
<html>
<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>
logout.php
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["name"]);
header("Location:login.php");
?>
No comments:
Post a Comment