Reputation: 41
I am trying to build a php login system with no databases being used. The system is build from 4 main php files, login.php, welcome.php and product.php and logout.php. in the navigation's bar of other pages, there is a "login" option, when clicking on it you are just being transfered into login.php file that contains the login form. I want to change the login to logout when getting the right password and username.
here is the code for login.php:
<form method="POST" action="login/welcome.php" class="form">
<h2 class="h2" style="text-align: center;">Login</h2>
<div class="input">
<input type="text" class="form-control" placeholder="username" name="username">
</div>
<br>
<div class="input">
<input type="password" placeholder="password" name="password">
</div>
<br>
<button type="submit" class="float" style="padding: 10px 15px;"><b>Submit</b></button>
</form>
And this is the code for welcome.php:
<?php
$username="admin";
$password="admin";
session_start();
if (isset($_SESSION['username'])){
header("Location: https://chessforu.000webhostapp.com/login/product.php");
}
else{
if ($_POST['username']==$username && $_POST['password']==$password){
$_SESSION['username']=$username;
echo "<script>location.href='welcome.php'</script>";
}
else{
echo "<script>alert('username or password incorrect!')</script>";
echo "<script>location.href='login.php'</script>";
}
}
This is the code for product.php:
<?php
session_start();
if (isset($_SESSION['username'])){
}
else {
echo "<script>location.href='login.php'</script>";
}
<html>
<body>
<p> Thanks for logging in! </p>
<div id="wrapper">
<nav>
<ul class="main_menu">
<li><a href="notimportant">Main Page</a>
<li><a href="notimportant">About Us</a>
<li><a href="notimportant">Contact us</a>
<li><a href="login/logout.php">Logout</a>
</ul>
</nav>
</div>
This is the code for logout.php:
<?php
session_start();
if (isset($_SESSION['username'])){
session_destroy();
echo "<script>location.href='login.php'</script>";
}
else{
echo "<script>location.href='login.php'</script>";
}
?>
Upvotes: 1
Views: 447
Reputation: 329
Just use a simple if statement
that determines what button/link to display (log in or log out) by simply checking the session to check if he is logged in or not.
To not repeat yourself, You can move the navigation bar to a single file, add your logic, and require this file whenever you want to add the navigation bar.
Upvotes: 1