I have three files
- index.php
- login.php
- auth.php
My login form is based on my index.php. i including the login.php on the index page.
i want it so when i log in, it will be authenticated by auth.php (which is does) and a message will be displayed on auth.php which says “Your login was successfully” (which is does), however, when it goes back to the index page it comes up with the login form instead of saying “Welcome USER you have successfully logged in.
I believe the error comes from the session mainly because i do not know what else could be wrong.
Here is my code of each page.
Index.php:
<?php include ("login.php"); ?>
login.php
<?php
if ($loggedin){
echo '<h2>Logged in</h2><p style="font-size:14px;">Welcome '.$user.' you have sucessfully logged in.</p>';
}
else {
echo '
<h2>Login</h2>
<form action="auth.php" method="POST">
<div class="smallform">
<p><span>Username:</span><br>
<input type="text" name="user"></p>
<p><span>Password:</span><br>
<input type="password" name="pass"></p>
<p style="padding-top: 15px"><input type="submit" value="Submit"></p>
</div>
</form>';
}
?>
Auth.php:
<?php
session_start();
$con = mysqli_connect("HoST", "USER", "PASS", "DBNAME");
$user = $_POST["user"];
$pass = $_POST["pass"];
$sql = "SELECT UserID FROM Customer
WHERE UserID = \"$user\"
AND Password = md5(\"$pass\")";
$res = mysqli_query($con, $sql);
?>
<!DOCTYPE>
<html>
<head>
<title>VeloCity</title>
<link href="_stylesheet.css" rel="stylesheet" type="text/css" />
<?php echo '<meta http-equiv="refresh" content="1;URL=index.php" />'; ?>
</head>
<body>
<div align="center">
<?php
if(mysqli_num_rows($res)==1){
$_SESSION["user"] = $user;
echo "You have sucessfully logged in";
}
else{
echo "You have entered an incorrect password. Please try again";
}
?>
</div>
</body>
</html>
Would really appreciate some help!
With sessions it’s best to put session_start(); right at the very top of the page. Line 1 as this avoids session setting errors.
On every page you make that you want restricted access to you will need to apply session_start(); on every page.
There after you can add your custom session rules. So after the database check you’d need to create a session variable within the Auth.php file like so:
Then for every other page you want to check that the session exists.
EDIT :
better validation;
apply that to the top of the index page and remove the include(Auth.php); that should work better.