I'm currently doing a simple project to make login and logout page in navbar but i can't change login link to logout in my homepage after logging in. Also I wrote these codes by youtube tutorials since i haven't learned php much. Here's my login.php file:
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users`
WHERE username='$username'
and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
// Redirect user to home page
header("Location: finalproject.php");
exit();
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='registration.php'>Register Here</a></p>
</div>
<?php
}
?>
Here's my logout.php file:
<?php
session_start();
// Destroying All Sessions
if(session_destroy())
{
// Redirecting To Home Page
header("Location: finalproject.php");
exit();
}
?>
finalproject.php is my homepage where i want to change navlink from login to logout. Here's the nav link tags:
<li class="nav-item">
<a class="nav-link" href="login.php">Login</a></li>
I tried changing this line to:
<li class="nav-item">
<?php
if(!isset($_SESSION['logged_in'])){?>
<a class="nav-link"><a href="login.php">Login</a></p>
<?php
} else {
?>
<a class="nav-link"><a href="logout.php">Logout</a></p>
<?php
}
?>