I'm trying to figure out how to implement a Log Out button into my code, but can't seem to figure out how to do it. Here is the code for my Log In page and Index page.
Index Page HTML
<?php
include("connectDatabase.php");
include("products.php");
?>
<?php
require "logincheck.php";
?>
<html>
<head>
<br><br>
<a href="resetPassword.php">Reset Password Page</a><br><br>
<a href="login.php">Login Page</a><br><br>
<a href="forgotPassword.php">Forgot Password Page</a><br><br>
<a href="logincheck.php">Login Check Page</a><br><br>
<a href="register.php">Register Page</a><br><br>
</head>
<body>
<h1> Small IT Business <h1>
Welcome <?php echo $_SESSION["email"] ?>.
</body>
</html>
Login In Page PHP
<?php
session_start();
if (isset ($_SESSION["email"]) && isset($_SESSION["loggedIn"])) {
header("Location: index.php");
exit();
}
if(isset($_POST["logIn"])) {
$connection = new mysqli("localhost", "root", "", "membershipsystem");
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$data = $connection->query("SELECT firstName FROM users WHERE
email='$email' AND '$password'");
if($data->num_rows > 0) {
$_SESSION["email"] = $email;
$_SESSION["loggedIn"] = 1;
header("Location: index.php");
exit();
}else{
echo "Please check your imputs!";
}
}
?>
<html>
<body>
<form actions="login.php" method="post">
<input type="text" name="email" placeholder="Email"/><br />
<input type="password" name="password" placeholder="Password"/><br
/>
<input type="submit" value="Log In" name="logIn" />
</body>
</html>
Create a logout.php
and destroy
the session there
<?php
session_start();
session_destroy();
echo 'You have been logged out';
Place logout link in all required pages.
<a href='logout.php'>Log out</a>
For logout you need to destroy session.
<?php
session_start();
session_destroy()
?>
<html>
<head></head>
<body>
<h1>You have been logged out.<h1>
</body>
</html>
Unset session by key (Similar to array unset)
//This will remove your custom session by key
unset($_SESSION['email']);
unset($_SESSION['loggedIn']);
Remove all session variables (similar to setting blank array $a = array(); )
session_unset();
Destroy the session (This will unset session and delete session file on the server.)
session_destroy();
Home.php
<?php
include 'connect_to_database.php';
// connect the connection page
if (empty($_SESSION)) // if the session not yet started
session_start();
if (!isset($_SESSION['email']))
{ //if not yet logged in
header("Location: login.php"); // send to login page
exit;
}
?>
<html>
<body>
Welcome <?php echo $_SESSION['email']; ?>, <a href="logout.php">logout</a>
</body>
</html>
Logout.php
<?php
session_start();
unset($_SESSION['email']);
unset($_SESSION['loggedIn']);
session_destroy();
header("Location: login.php");
exit;
?>