Hi,
I’m currently having an issue with validating my login script, it only appears that one part of it actually works!
I have a simple login form with a username and password field and login button.
At the moment if I enter nothing into the login form (nothing for both username and password), it logs in as an unregistered user with no ID and my error message is displayed.
If I enter an unregistered username with no password the same thing happens.
If I enter an unregistered username with a random password there is no log in which is good, but my error message is not displayed.
If I enter a registered username and password into the form, it logs in with the correct ID and no error message is displayed, which is good.
If I enter a random password with nothing in the username it does not log in which is good and the error message is displayed as it should.
How can I get it so that all of these login attempts are coded so that it always results in the last case if an unregistered user is entered and / or missing details are entered into the form?
Form and Validation Code
[php] <?php
if ($_SESSION['loggedin'] == true){
echo "You are logged in as ";?><b><?php echo $_SESSION['username']?></b><?php echo " ["; echo $_SESSION['id']; echo "]";
?>
<a href="logout.php">Logout</a>
<?php
}else{
echo "<p><b>Login:</b></p>\n";
?>
<form name="loginform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<b>Username:</b> <input type="text" name="liusername">
<b>Password:</b> <input type="password" name="lipassword">
<input type="submit" name="lisubmit" value="Login">
</form>
<?php
}
if ($_SESSION['loggedin'] == true);
if (empty($_POST) === false) {
$username = $_POST['liusername'];
$password = $_POST['lipassword'];
if (empty($username) === true || empty($password) === true) {
?><br /><font color="red"><?php echo 'ERROR: You need to enter a username and password!';
}
}
?>[/php]
Login Code
[php]<?php
if (isset($_POST['lisubmit'])){
$query = "SELECT user_id, user_password FROM user WHERE user_username = '".$_POST['liusername']."'"; // Select details from user table
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row['user_password'] == $_POST['lipassword']) {
$_SESSION['loggedin'] = true;
$_SESSION['id'] = $row['user_id'];
$_SESSION['username'] = $_POST['liusername'];
} else {
$_SESSION['loggedin'] = false;
$_SESSION['id'] = 0;
}
}
[/php]
I’m still a newbie towards php so I’m not sure what/where to add or change as I don’t understand this validation thing very well?
How do I check that the user exists and how do I stop random user names that are not in the user table from logging in? Thanks.
Thank you in advance for any help