0

I am trying to create a login form, but the username and password validation isn't working properly. $AccountValidation is always returning 0, while I am positive I filled in the right password and username. First a user has to register with more variables (i.e. first name) then they can go to the login.html page and then they go to the file below login.php.

I have var_dumped all variables and all are coming through nicely.

$Username = strip_tags($_POST['Username']);
$Password = md5(strip_tags($_POST['Password']));

if(empty($Username) || empty($Password)) die('Vul alle waarden in op <a href="login.php">het formulier</a>.');

$db = new mysqli($host, $user, $pass, 'accounts', 3306);

$sql = "SELECT Username, Password FROM users where Username = '$Username' AND Password = '" . $Password . '\'';
$results = $db->query($sql);

$AccountValidation = $results->num_rows;

if($AccountValidation == 1)
{
$_SESSION['login'] = 'yes';
header('location: xxxxx');
}   else{
    echo'Your account does not exist or you have not filled in the required    information.<br> Retry <a href="Login.html">here</a> or create a new account <a href="GetInfo.html">here</a>';
}
?>

var_dump $results

object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) }

var_dump $AccountValidation

int(0)

Edit:

Found the solution. MD5 has 32 characters and I allowed only 20 for a password to be uploaded to MySQL. Sometimes it can be this stupid...

Kevin
  • 204
  • 1
  • 12
  • 1
    note: Use bcrypt or something, but not md5...using md5 is pointless – dayuloli Mar 20 '14 at 15:18
  • I know, I am first creating a main script then I will add more security ;). But thanks for suggesting! – Kevin Mar 20 '14 at 15:20
  • 3
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Mar 20 '14 at 15:20
  • 2
    You are using [an unsuitable hashing algorithm](http://php.net/manual/en/faq.passwords.php) and need to [take better care](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) of your users' passwords. – Quentin Mar 20 '14 at 15:21
  • 3
    You should not manipulate the user-sent username and password. Instead you should do validation on the original input (for the username) and use prepared statements to avoid sql injection. Also note that `$Password` will never be empty because `md5('') === "d41d8cd98f00b204e9800998ecf8427e"` – jeroen Mar 20 '14 at 15:21
  • 2
    Don't build it wrong, throw out half your code and rebuild it right, that's just a waste of time. Do the right thing from the outset. – Quentin Mar 20 '14 at 15:21
  • Why do you have a `\\` at the end of your SQL? – ElefantPhace Mar 20 '14 at 15:21
  • @Quentin I am doing that on purpose. I want to be able to see where code can be improved and keep on improving that. Because that's where I will be trained for. This project will never go live, it's just something I want to learn. I am open too suggestions though – Kevin Mar 20 '14 at 15:25
  • Sidenote: You have a missing semi-colon at the end of `header('location: xxxxx)` @Ajaxkevi Plus, is `session_start();` loaded? – Funk Forty Niner Mar 20 '14 at 15:36
  • @Fred-ii- I am aware. I replaced the real http:// with xxx so it doesn't show my directory's here ;). – Kevin Mar 20 '14 at 15:37
  • Try changing your query to `$sql = "SELECT Username, Password FROM users where Username = '$Username' AND Password = '$Password'";` what you have now is incorrect. Your query opens with a double quote and ends with a `'\''` – Funk Forty Niner Mar 20 '14 at 15:41
  • 1
    @Fred-ii- Does not work. But thanks for spotting that error. I know the semicolon is missing. It's not missing on my actual file. A thing I replaced before posting. I added the semicolon in my question now. – Kevin Mar 20 '14 at 15:43
  • Try printing your SQL query and running it to the database yourself and see how many rows you get. If you get more than 0 rows back, try to see what `$results->num_rows` returns. Or just `print_r($results)` – Alex van den Hoogen Mar 20 '14 at 15:47
  • don't you need to fetch the result first ? – Dwza Mar 20 '14 at 15:51
  • Try `where Username = '$Username' AND password = '".md5(mysql_real_escape_string($Password))."'` Or `where Username = '$Username' AND password='".md5($Password)."'` that should make it kick into gear. @Ajaxkevi – Funk Forty Niner Mar 20 '14 at 16:06
  • $Fred-ii That creates this error: Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\PHP\htdocs\Adlantic\LoginSystem\login.php on line 27. line 27 being: $_SESSION['login'] = 'yes'; – Kevin Mar 20 '14 at 16:14
  • Try `$sql = "SELECT Username, Password FROM users WHERE Username='".$Username."' AND Password='".md5($Password)."'";` – Funk Forty Niner Mar 20 '14 at 16:26
  • @Fred-ii- No error but same results :(. – Kevin Mar 20 '14 at 16:29
  • I edited my comment above; I forgot to put `Password` in select. Or Try `$sql = "SELECT * FROM users WHERE Username='".$Username."' AND Password='".md5($Password)."'";` – Funk Forty Niner Mar 20 '14 at 16:29
  • Your edit did something. In the var_dump it made ["field_count"]=> int(2) instead of int(0). But I am still getting a 0 for the $AccountValidation variable. Your next suggestion created int(6), Which is weird because I have 5 entries. – Kevin Mar 20 '14 at 16:33
  • What if you tried `if($AccountValidation > 0)` – Funk Forty Niner Mar 20 '14 at 16:37
  • Wouldn't work as $AccountValidation == 0 – Kevin Mar 20 '14 at 16:38
  • Are you open to using a different method/version of a login method using MD5? – Funk Forty Niner Mar 20 '14 at 16:40
  • If you are open to another method using MD5, I have a working version if you want me to post it as an answer. @Ajaxkevi – Funk Forty Niner Mar 20 '14 at 16:52

1 Answers1

0

N.B.: This answer has been given as an alternate method using MD5 (presently used).

Both the OP and I are well aware of the risks involved.

"I am doing that on purpose. I want to be able to see where code can be improved and keep on improving that. Because that's where I will be trained for. This project will never go live, it's just something I want to learn. I am open too suggestions though."


(Tested)

Username and password creation script:

<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');  
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');

$mysqli = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) 
OR die("could not connect");

$username = "user";
$password = "12345";
$md5_pass = md5($password);

$result = mysqli_query($mysqli,"INSERT INTO users (username, password) VALUES ('$username', '$md5_pass') ") or die(mysqli_error());

if($result){
echo "Success";
}

else{
echo "Sorry";
}
?>

Login script: (SQL/HTML as a single file)

<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');  
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');

$mysqli = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) 
OR die("could not connect");

if(isset($_POST['submit'])){
// Grab User submitted information
$name = mysqli_real_escape_string($mysqli,$_POST["users_name"]);
$pass = mysqli_real_escape_string($mysqli,md5($_POST["users_pass"]));

 $result = mysqli_query($mysqli,"SELECT username, password FROM users WHERE username = '$name' AND password='$pass'");

$row = mysqli_fetch_array($result);

if($row["username"]==$name && $row["password"]==$pass){
    echo"You are a validated user.";
    }
else{
    echo"Sorry, your credentials are not valid, Please try again.";
    }

} // if(isset($_POST['submit'])){
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
    <form method="post" action="">
        <table border="1" >
        <tr>
            <td><label for="users_name">Username</label></td>
            <td><input type="text" 
              name="users_name" id="users_name"></td>
        </tr>
        <tr>
            <td><label for="users_pass">Password</label></td>
            <td><input name="users_pass" type="password" id="users_pass"></input></td>
        </tr>
        <tr>
            <td><input type="submit" name="submit" value="Submit"/>
            <td><input type="reset" value="Reset"/>
        </tr>
    </table>
</form>
</body>
</html>

Disclaimer:

It is best to use mysqli_* functions with prepared statements or PDO, plus using either crypt() or PHP 5.5's password_hash() function for password storage.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141