I have a login form that displays a message when a user either registers or logins in. I would like the login page to open first and after successful login then index.php can be shown. also should someone try and access /index.php directly it must still direct them to login.php to be authenticated. I have tried some examples of other peoples codes but i cannot get the page to authenticate the user.
My Login.php code:
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$sql = "SELECT * FROM `login` WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['username'] = $username;
}else{
$fmsg = "Invalid Username/Password";
}
}
if(isset($_SESSION['username'])){
$smsg = "User already logged in";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Login in PHP & MySQL</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container">
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<form class="form-signin" method="POST">
<h2 class="form-signin-heading">Please Register</h2>
<div class="input-group">
<input type="text" name="username" class="form-control" placeholder="Username" required>
</div>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholde r="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
<a class="btn btn-lg btn-primary btn-block" href="register.php">Register</a>
</form>
</div>
</body>
</html>
You can if statement to check whether user is login or not. If user is not logged in then you can redirect them to login.php If user is logged in then you can let them see index page. To do so, code example is given below....
<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
$welcomeMessage = "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
header('Location: login.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Index page</title>
</head>
<body>
<?
if(!empty($welcomeMessage)) echo $welcomeMessage;
?>
Index page
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With