I have made a login script, that allows the user to enter a username and password in an HTML form. The two variables are checked in a MySQL dbase and if they are correct used in a session.
In the pages I want to protect I include a file that checks the variables in the session with those from the dbase.
The two scripts look like this:
auth.php:
<?
session_start();
addslashes($username);
addslashes($passcode);
$password = md5($passcode);
require("$DOCUMENT_ROOT/lib/mysql.inc.php");
mysql_connect($mysqlhost,$mysqlusr,$mysqlpass);
mysql_select_db($dbname);
$passquery = mysql_query("SELECT password, id FROM profiler WHERE username = '$username'");
if (!mysql_num_rows($passquery))
{
header("location: /lib/login_error.php");
exit;
}
else
{
if($row = mysql_fetch_array($passquery))
{
$dbpassword = $row["password"];
$profilid = $row["id"];
}
if($dbpassword == $password)
{
$login = (true);
}
if ($dbpassword != $password)
{
header("location: /lib/login_error.php");
exit;
}
session_register(username);
session_register(password);
session_register(profilid);
header("location: /admin/index.php");
exit;
}
?>
secure.php
<?
session_start();
require("$DOCUMENT_ROOT/lib/mysql.inc.php");
mysql_connect($mysqlhost,$mysqlusr,$mysqlpass);
mysql_select_db($dbname);
$passquery = mysql_query("SELECT password FROM profiler WHERE username = '$username'");
if (!mysql_num_rows($passquery))
{
header("location: /lib/login_error.php");
exit;
}
else
{
$row = mysql_fetch_array($passquery);
$dbpassword = $row["password"];
if($dbpassword == $password)
{
$login = (true);
}
if ($dbpassword != $password)
{
header("location: /lib/login_error.php");
exit;
}
}
?>
The script works more or less the way I want it to. However when a user logs in the first time it gives an error, though the password is correct. If the user then enters the same username/password again it all works.
What is wrong since you have to enter the words twice or at least reload the page?