2

This is the first time I'm using PHP and MySQL to make a login system where a person can enter username and password and the php scripts checks if the username and password exists in the database.

When the user enters the correct info It displays the "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..." message which is all good. But if the user enters in the wrong info, the "SORRY...YOU ENTERED WRONG ID AND PASSWORD...PLEASE RETRY..." message should appear but the page is blank. Why is that?

<?php
define('DB_HOST','localhost');
define('DB_NAME','test'); //name of database
define('DB_USER','root'); //mysql user
define('DB_PASSWORD',''); //mysql password

$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
}
$db = mysqli_select_db($con,DB_NAME) or die(mysqli_connect_error()); 

/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn(mysqli $con){
    session_start(); //starting the session for user profile page
    if(!empty($_POST['user'])){ //checing the 'user' name which is from Sign-in.html, is it empty or have some text
        $query = mysqli_query($con,"SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysqli_connect_error());
        $row = mysqli_fetch_array($query) or die(mysql_error());
        if(!empty($row['userName']) AND !empty($row['pass'])){
            $_SESSION['userName'] = $row['pass'];
            echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
        }
        else{
            echo "SORRY...YOU ENTERED WRONG ID AND PASSWORD...PLEASE RETRY...";
        }
    }
}

if(isset($_POST['submit'])){
    SignIn($con);
}
?>
Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
kws3778
  • 329
  • 3
  • 18
  • Why are you making the session user name equal to the password? `session_start()` must be at the very top of the file, not inside a function. – Jay Blanchard Feb 20 '15 at 22:38
  • 4
    Just as a cautionary exercise, what would happen if my username was "`1'; DROP DATABASE UserName; --`"? – castis Feb 20 '15 at 22:38
  • @castis SQL Injection – André Ferraz Feb 20 '15 at 22:40
  • @Kevin Shen — you should be using PDO and prepared statements to avoid SQL injection – Andy Fleming Feb 20 '15 at 22:41
  • 1
    My entered password would be `' OR 1=1` - an easy way to log in as any user I choose! – halfer Feb 20 '15 at 22:42
  • 2
    You should also be hashing your passwords using a suitable algorithm - plaintext is not really good enough, since if the database is stolen, your users might be exposed to impersonation on their other accounts (because, unfortunately, many users use the same email/password combination across sites). – halfer Feb 20 '15 at 22:44

2 Answers2

3

Firstly, I have to state that your code is highly prone to SQL injection <= do read that, not to mention storing passwords in plain text which is highly discouraged.

  • Do not store passwords in plain text, you will eventually get hacked.

  • Consult my footnotes about all of the above, regarding injection and password storage.

You're also mixing MySQL APIs with mysql_error() which doesn't intermix with mysqli_ functions. It needs to be mysqli_error($con).


Now, your code is failing because of this line:

if(!empty($row['userName']) AND !empty($row['pass']))

Even though a person enters a wrong or inexistant username and/or password, it will still remain TRUE because those rows are NOT empty.

Therefore it never gets to enter the else part of your script.

To get you started, here is what you need to do:

Replace:

if(!empty($row['userName']) AND !empty($row['pass']))

with:

$row = mysqli_fetch_array($query);
    $username = $row['userName'];
    $pw = $row['pass'];

if($user==$username && $pass==$pw) {
// $user and $pass are from POST
// $username and $pw are from the rows

    $_SESSION['userName'] = $row['pass'];

    echo "Successfully logged in.";
    }

else { echo "Invalid."; }

While using the following inside the SignIn() function:

$user = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);

and replacing your query with:

$query = mysqli_query($con,"SELECT * FROM UserName 
        where userName = '$user' 
        AND pass = '$pass'") 
        or die(mysqli_connect_error());

Footnotes:


Edit:

Oh yea and also I changed my code to yours, but now everytime I login It displays Invalid, even with the right username and password. Any ideas?It seems to be failing the if($user==$username && $pass==$pw) if statement.

Here's what I used to test it with, you can replace the DB credentials with your own and other adjustments, since I did not use a form, but hard-coded values.

This did in fact jump in the else if an incorrect user/password was entered.

<?php 
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die(mysqli_connect_error());

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
}

 function SignIn($con){

$_POST['user'] = "John";
$user = $_POST['user'];

$_POST['pass'] = "12345";
$pass = $_POST['pass'];

   // session_start(); //starting the session for user profile page
   if(isset($_POST['user'])){

$query = mysqli_query($con,"SELECT * 
        FROM UserName where userName = '$_POST[user]' 
        AND pass = '$_POST[pass]'") 
        or die(mysqli_connect_error());


$row = mysqli_fetch_array($query);
    $username = $row['userName'];
    $pw = $row['pass'];

if($user==$username && $pass==$pw) {
    echo "Successfully logged in.";
    }

else { echo "Invalid"; }


    } // brace for isset post user

} // brace for function

if(isset($_POST['submit'])){
   echo SignIn($con);
}
?>
Community
  • 1
  • 1
Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
  • Works, Thanks! This is just a test script. I will add the proper security measures to avoid SQL injections. – kws3778 Feb 21 '15 at 17:32
  • Oh yea and also I changed my code to yours, but now everytime I login It displays Invalid, even with the right username and password. Any ideas?It seems to be failing the if($user==$username && $pass==$pw) if statement. – kws3778 Feb 21 '15 at 21:28
  • @KevinShen Reload the answer and look near the bottom under **Edit:**. This is what I used to test it with and it worked correctly. – Funk Forty Niner Feb 21 '15 at 22:39
  • Yep it works. I found the source of the error. It seems to be that i cant use $user and $pass in the query line and I had to use $_POST[user] and $_POST[pass] – kws3778 Feb 22 '15 at 14:28
  • @KevinShen Ok. Problem solved. Can you mark my answer as solved so we can close the question. – Funk Forty Niner Feb 22 '15 at 14:31
0

Before I get to the actually answer to you question, I would recommend you to use mysqli_real_escape_string() for both username and password. You could use PDO which does it all for you and in my opinion is less work.

The problem you have is that your forgot to add another else block on the first if statement.

if(!empty($_POST['user'])) { 
    // first block
    if(!empty($row['userName']) AND !empty($row['pass'])) {
       // first inner block  
    } else {

    }
} else {
  // this else is what your missing
}
André Ferraz
  • 1,471
  • 11
  • 28