I have a login page where I've set a query to check if the login & password entered match the database. The user should only be able to see the homepage if they are logged in.
The PHP Login validation on the login page works fine (if user/pass does not exist, it shows the error message. If the combination is correct, it redirects to the homepage just as it should):
LOGIN PAGE
<?php
define('DB_LOCATION', 'x');
define('DB_USERNAME', 'x');
define('DB_PASS', 'x');
define('DB_NAME', 'x');
$dbc = mysqli_connect(DB_LOCATION, DB_USERNAME, DB_PASS, DB_NAME)
or die('Error connecting to database');
$error_message= "";
$user_name = $_POST['user'];
$user_password= $_POST['pass'];
if (isset($_POST['submit'])) {
// ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
if(!empty($user_name) && !empty($user_password)) {
$query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";
$result = mysqli_query($dbc, $query)
or die ('Error querying username/password request');
if(mysqli_num_rows($result) == 1) {
session_start();
$_SESSION['user'] = $row['user'];
$_SESSION['pass']= $row['pass'];
header("Location: http://test.ishabagha.com/LESSON5/3%20-%20HOMEPAGE%20:%20WELCOME.php");
} // end if rows
else {
$error_message = "You were not able to log in";
} // end else
} // end query
} // end isset
?>
My issue is that on the homepage, I want to make it so that if the username and password have not been set/accepted, it redirects back to the login page and the homepage is not viewable. This is what I put in the PHP header - even if I haven't previously logged in, it still shows the page instead of directing it back to the login page (where he header/location is specified) and does not keep the home page private.
HOMEPAGE
<?php
define('DB_LOCATION', 'x');
define('DB_USERNAME', 'x');
define('DB_PASS', 'x');
define('DB_NAME', 'x');
$dbc = mysqli_connect(DB_LOCATION, DB_USERNAME, DB_PASS, DB_NAME)
or die('Error connecting to database');
session_start();
$user_name = $_SESSION['user'];
$user_password= $_SESSION['pass'];
if(!isset($_SESSION['user']) && !isset($_SESSION['pass'])) {
header("Location: /LESSON5/1%20-%20LOGIN.php");
}
?>
Please let me know what it is is that could be causing the second part of the code on the homepage from redirecting.