Page 1 of 1

Is this login code secure?

Posted: Sat Oct 25, 2008 6:14 am
by yoji
Hi I just wrote this code yesterday. I am not sure whether It's secure or not. I just made it up... Works fine enough. I just wanted to know if it is secure or should i change anything? Anything I can do to make it better?
I know it won't do anything right now except to echo whether you are logged in or not. The password and user are insecure too. I just want to know about the rest of the code.. Is it a good enough way?

Code: Select all

 
<?php
$host="localhost";
$user="root";
$pass="";
$db="mydiary";
$ip=$_SERVER['REMOTE_ADDR'];
 
$con = mysql_connect($host,$user,$pass);
//connection to database
if (!$con)
{
    die('couldnt connect'.mysql_error());
}
else
{
    mysql_select_db ($db,$con);
}
/////////////////////////////////////////////
/////////////////////////////////////////////
//Function to compare username and password from database
 
function checkuserpass($fuser,$fpassword)
{
    $result = mysql_query("SELECT * FROM Authentication");
    while($row = mysql_fetch_array($result))
    {
        if ($row['username']==$fuser and $row['password']==$fpassword)
        {
            echo "you are authenticated";
        }
        else
        {
            echo "error in password or user";
        }
    }
 
}
/////////////////////////////////////////////
//Just a variable for displaying the error if the length is too small,
// It is used in the conditional statement later.
$lengthError="
<script type=\"text/javascript\">
alert(\"Username and password should be longer than 3 characters\")
</script>";
////////////////////////////////////////////
if (isset($_POST['Submit']))
{
    $username=$_POST['username'];
    $password=$_POST['password'];
    
    if (strlen($username)<3 or strlen($password)<3) // To check the length of the username and password
    {
        echo $lengthError;
    }
        else
    {
        checkuserpass($username,$password); // Function created above to check for user and pass from database
    }
}
?>
 

Re: Is this login code secure?

Posted: Sat Oct 25, 2008 7:32 am
by Hannes2k
Hi,
your login seems to be secure, but it is inefficient, cause if you had 10 000 users, you have to check 10 000 records (and also if you entered a valid username+password, you get 9 999 error messages).
And saving the password in plaintext in the database isn't a good idea. Use a hash algorithm, best with a salt.

To make your login more efficient use WHERE in your SQL Statement:
$result = mysql_query("SELECT * FROM Authentication WHERE username = '".mysql_real_escape_string($fuser)."'");