What is PHP?
- The PHP (Hypertext Preprocessor) is a server scripting language, used for making dynamic web pages.
- PHP is an open source software and it is free to download and use.
- PHP supports a wide range of databases like MySQL, Oracle, Sybase, Solid, PostgreSQL etc.
PHP Login logout example with session
In this login logout example in PHP we used three 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
<?php
session_start();
$message="";
if(count($_POST)>0) {
$con = mysqli_connect('localhost','root','','gpkumardb') 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
<?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");
?>