I have a login page(checklogin.php) that leads to my website's homepage(index.php) on successful sign in. In order to ensure that index.php (& every page in the website) can only be accessed through the login page, i've made use of a session variable which is checked at the start of index.php as follows:
<?php
session_start();
if( !isset($_SESSION['myusername']) )
header("location:checklogin.php");
?>
After adding this, logging in through checklogin.php results in an error('wrong username, password' - even thought both are approved); when i get rid of the above session code in the index.php, the homepage opens without error.
Below is the code in checklogin.php:
<?php
$host="localhost"; // Host name
$username="garbo45"; // Mysql username
$password="water5"; // Mysql password
$db_name="garbo45"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) die($conn->connect_error);
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysqli_real_escape_string($conn, $myusername);
$mypassword = mysqli_real_escape_string($conn, $mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count=mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "loginsuccess.php"
$_SESSION['myusername']= "myusername";
$_SESSION['mypassword']= "mypassword";
header("location:index.php");
}
else {
echo "Wrong Username or Password";
}
?>
Why is the session code block in the index.php causing this error when the username and password (which i've verified is among those set in the members table) goes through as soon as the session checking is removed? Would appreciate any help in understanding and addressing this.