I am taking my first steps into php and I have come across this unsolvable for me problem. I am trying to create a website which uses a simply MySQL database to identify some credentials given by the visitor. Please note that at this point I am not really interested about the overall security of the website. Now to the problem:
Suppose I have 3 files.
In file main_login.php the form that the user must use to enter the website is stored, which is calling checklogin.php:
<form name="form1" method="post" action="checklogin.php">
In checklogin.php I am checking whether the input (Name and Password) given by the user is contained on the database and if that’s correct I am redirecting him to index.php:
// More unrelated php here....
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_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 "index.php"
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("location:index.php");
}
else
{
echo "Wrong username or password";
}
Finally in index.php I am checking if the `$_SESSION[username]’ is defined, otherwise I redirect the user to the main_login.php.
<?php
session_start();
if (!isset($_SESSION['username']))
{
header("location: main_login.php");
}
?>
// HTML code here...
The problem now: Perhaps I have put too many hours into this and I can’t think clearly but whenever I input the correct password and username I am always redirected to main_login.php, unlike when I put the wrong credentials. Anyone likely to solve this?
It looks like you haven’t started the session when you are setting the session variables on the checklogin page. This means that
$_SESSION['username']will not be set once they get redirected to the index page.