I’ve just started getting into sessions, but i’m confused whether you need to declare each variable at the top when using forms.
I have this code below. The logic behind is it that when it first runs, none of the ‘if ‘conditions apply, so it will display the login form. When the user submits the button it reactivates the same script, only this time there will be a userid and password to authenticate.
Yet when i click submit, with valid username and passwords, it just reloads the form as if the username and password were incorrect.
I was wondering if this is because i need to declare the variables in the script using $var = $_POST[‘var’]. If so, where would these go in the script, cos when i put them at the top i get a header error.
Heres the code:
<?
session_start();
if ($userid && $password)
{
//if the user has just tried to log on
$dbcnx = mysql_connect(“localhost”, “root”);
msql_select_db(“ccf”, $dbcnx);
$query = “select * from user where name = ‘$userid’ and password = ‘$password'”;
$result = mysql_query($query, $dbcnx);
if (mysql_num_rows($result) > 0)
{
//if they are in the db register the user id
$valid_user = $userid;
session_register(“valid_user”);
}
}
?>
<HTML>
<h1>Customer Login</h1>
<?
if (session_is_registered(“valid_user”))
{
echo “You are logged in as : $valid_user <br>”;
echo “<a href = “logout.php”>Log Out</a><br>”;
}
else
{
if (isset($userid))
{
//if they tried but failed to log on
echo “Could not log you in”;
}
else
{
//they have not tried to log in or are logged out
echo “You are not logged in<br>”;
}
//login form
echo “<form method = post action =”authmain.php”>”;
echo “<table>”;
echo “<tr><td>User ID:</td>”;
echo “<td><input type = text name = userid</td></tr>”;
echo “<tr><td>Password:</td>”;
echo “<td><input type = password name = password></td></tr>”;
echo “<tr><td colspan = 2 align = center>”;
echo “<input type = submit value =”Log in”></td></tr>”;
echo “</table></form>”;
}
?>
<br>
<a href = “members_only.php”>Members Section</a>
</body>
</html>