0

Here is my back end for the login page it first checks the username against the database if the user exists if checks the password against the user in the data base if they match we log in if they don't we don't log in. And that part works fine however if the username does not exist (and I wrote something that is supposed to catch that) I get a blank white page which is not the intended result. Can someone point out where it is that my code is breaking??

<?php

/*
 Handles Login Requests  
*/

define('DB_HOST', 'localhost');
define('DB_NAME', 'sec_usr');
define('DB_USER', 'sec_usr');
define('DB_PASS', 'n89tzAh2w3Uf4GUu');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());

/*
 $ID=$_POST['user'];
 $Password = $_POST['pass'];
*/

function LogIn()
{
     session_start();
    if(!empty($_POST['user']) && !empty($_POST['pass'])) 
    {
        $query = mysql_query("SELECT * FROM username where userName = '$_POST[user]'") or die(mysql_error());
        $row = mysql_fetch_array($query) or die(mysql_error());
        if(!empty($row['userName']))
        {
            if($row['userPass'] === $_POST['pass'])
            {
                echo"Success"; /* Works */
            }
            else
            {
                echo"Wrong Pass"; /* Works */
            }
        }
        else
        {
            echo"Wrong User"; /* Does Not Work */
        }
    }      
}

if(isset($_POST['submit']))
{
    LogIn();
}

?>

I had added a piece to my question after I had asked the initial question as to how to use the mysqli but my original question which I have reverted the question back to had nothing to do with using mysqli I had figured that if people were telling me to use mysqli I may as well ask those same people how to use it not how to use them together.

H3rcu135
  • 11
  • 4
  • 1
    throw this crap out and use mysqli or pdo – Drew Jun 19 '15 at 23:00
  • You're not escaping user input in your queries and you're storing unhashed passwords in the database. If you're planning on putting this into production, don't. Use an existing solution that handles user management properly instead. – Mathew Tinsley Jun 20 '15 at 00:00
  • To remove the duplicate flag on your question, I suggest you edit it and take out the `mysqli` part that wasn't part of the problem, explain this briefly in the "Edit Summary", then your question can be unmarked (reference: [Someone flagged my question as already answered, but it's not](http://meta.stackexchange.com/questions/194476/someone-flagged-my-question-as-already-answered-but-its-not)). – Marcos Dimitrio Jun 20 '15 at 03:20
  • Also, after reading again the link I provided above, I suppose it would be helpful to add a sentence to the end of the question itself explaining that you reverted the edit where you included additional questions about the use of mysqli, rolling back to the original question which doesn't have anything to do with mysqli, thus rendering the duplicate flag for "[Can I use “mysql_” and mysqli together?](http://stackoverflow.com/questions/17498216/can-i-use-mysql-and-mysqli-together)" incorrect. – Marcos Dimitrio Jun 22 '15 at 03:38
  • @MarcosDimitrio thanks for the advice because my question was not intended to be seen as a duplicate just thought that if i was being told use mysqli instead of mysql then those same people may be able to tell me how to adjust my code accordingly to get the same result – H3rcu135 Jun 26 '15 at 13:03

2 Answers2

0

Instead of using the !empty() check for the query, I'd suggest you use mysql_num_rows() to fetch the number of rows and then check if it is greater than 0.

empty() returns true if the variable is either FALSE or it is not set.

You could try this:

$query = mysql_query("SELECT * FROM username where userName = '$_POST[user]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
$num = mysql_num_rows($row);
if($num)
{
  \\username exists.
}
else
{
  \\username does not exist.
}

EDIT: Also, I'd advise you move to mysqli or PDO as they are more secure. Using mysqli won't be very different from mysql except for a few changes but you'd benefit a whole lot more from mysqli than mysql.

mysql v/s mysqli

For starters,

mysql_connect(host, username, password)
mysql_select_db(db)

changes to

mysqli_connect(host, username, password, db)

and

mysql_query(query)

changes to

mysqli_query(connect, query)

So, as you see, there aren't major differences, just minor ones. You could easily shift to mysqli.

Updated code with mysqli

<?php

define('DB_HOST', 'localhost');
define('DB_NAME', 'sec_usr');
define('DB_USER', 'sec_usr');
define('DB_PASS', 'n89tzAh2w3Uf4GUu');

$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Failed to connect to MySQL: " . mysqli_error($con));


/*
 $ID=$_POST['user'];
 $Password = $_POST['pass'];
*/

function LogIn()
{
 session_start();
 if(!empty($_POST['user']) && !empty($_POST['pass'])) 
 {
    $query = mysqli_query($con, "SELECT * FROM username where userName = '$_POST[user]'") or die(mysqli_error($con));
    $row = mysqli_fetch_array($con, $query) or die(mysqli_error($con));
    $num = mysqli_num_rows($con, $query);
    if($num)
    {
        if($row['userPass'] === $_POST['pass'])
        {
            echo"Success"; /* Works */
        }
        else
        {
            echo"Wrong Pass"; /* Works */
        }
    }
    else
    {
        echo"Wrong User"; /* Does Not Work */
    }
 }      
}

if(isset($_POST['submit']))
{
  LogIn();
}

?>
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
Akshay Khetrapal
  • 2,586
  • 5
  • 22
  • 38
  • I'm new to using databases how do I use mysqli or PDO?? and how do I get either of them? – H3rcu135 Jun 19 '15 at 23:03
  • mysqli is just a set of functions very similar to mysql while PDO or PHP Data Objects is a PHP extension. If you're new, you should start with mysqli for now. I'll edit my answer to add a few differences between mysql and mysqli which should help you. – Akshay Khetrapal Jun 19 '15 at 23:06
  • is mysqli part of the php code alone or does it involve changes to the database too? – H3rcu135 Jun 19 '15 at 23:11
  • It is a part of your code. You do not have to make ANY changes whatsoever at your database side in order to use mysqli. – Akshay Khetrapal Jun 19 '15 at 23:11
  • do I make any changes to how i make an array or get the number of rows?? I have made the change to mysqli and now all I get is wrong user – H3rcu135 Jun 19 '15 at 23:17
  • thank you for your help with mysqli – H3rcu135 Jun 19 '15 at 23:23
0

As you pointed out yourself on the comments, the problem is in this part:

$row = mysql_fetch_array($query) or die(mysql_error());

The PHP function mysql_fetch_array() returns FALSE if there are no rows found. When the user doesn't exist, the query will return FALSE, and PHP will execute the part after or. The problem is that there is no error for mysql_error() to display, since the query executed successfully, that's why you get an empty page.

To fix it, you could do:

$row = mysql_fetch_array($query);
if($row)
{
    if($row['userPass'] === $_POST['pass'])
    {
        echo "Success";
    }
    else
    {
        echo "Wrong Pass";
    }
}
else
{
    echo "Wrong User";
}

To be on the safe side, in case you don't receive either the user or the pass variable, you can also add an Exception in the previous if:

if(!empty($_POST['user']) && !empty($_POST['pass'])) 
{
    // query the database...
}
else
{
    // Code will most likely not reach here.
    throw new Exception("Form submitted but user/pass not received.");
}

Also, be aware that mysql_query("SELECT * FROM username where userName = '$_POST[user]'") is open to a SQL injection attack, you must escape the username before using it inside a SQL query. You can read more about it on the mysql_real_escape_string page. Can be done like this (taken from that page):

$query = sprintf("SELECT * FROM username where userName = '%s'",
    mysql_real_escape_string($_POST[user])
);
mysql_fetch_array($query);

And last, the Original MySQL API is deprecated as of PHP 5.5.0, it's recommended that you use MySQLi or PDO_MySQL extension.

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
  • the code right now is just on a private server and will be updated before going live any vulnerabilities are just to make things easier during initial testing – H3rcu135 Jun 19 '15 at 23:12
  • and I realized my initial problem if the query can't return a row then i get a msqli error so if i take out the or die I get the desired result – H3rcu135 Jun 19 '15 at 23:26
  • Yes, the problem was the `or die(...)` part, I'll update my answer to reflect that. – Marcos Dimitrio Jun 20 '15 at 03:03