I have been coding a basic PHP Login script just for testing purposes.
<?php
require 'config.php';
require 'connect.php';
// username and password sent from form
$tbl_name = 'users';
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
$_SESSION["username"];
$_SESSION["password"];
header("location:../../home.php");
}
else {
echo "Wrong Username or Password";
}
?>
I am able to get through this with no problem, but when it redirects to home.php, here is the code I have to check if session is not registered.
<?php
session_start();
if (!$_SESSION['username']) {
header("location:../../index.php");
}
?>
From what I understand, this is supposed to check if the user is not logged in, however when I login it still redirects me to index.php. How can I make sure the session is registered and nothing happens (i.e. I stay on home.php with no redirect, but I'm still logged in.)