0
 <?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$bool = true;

mysql_connect("localhost", "root", "") or die (mysql_error()); //Connect to server
mysql_select_db("first_db") or die ("Cannot connect to database"); //Connect to database
$query = mysql_query("Select * from users WHERE username='$username'"); // Query the users table
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "":
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
   while($row = mysql_fetch_assoc($query)) // display all rows from query
   {
      $table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
      $table_password = $row['password']; // the first password row is passed on to $table_password, and so on until the query is finished
   }
   if(($username == $table_users) && ($password == $table_password))// checks if there are any matching fields
   {
      if($password == $table_password)
      {
         $_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
         header("location: home.php"); // redirects the user to the authenticated home page
      }
   }
   else
   {
    Print '<script>alert("Incorrect Password!");</script>'; // Prompts the user
    Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
   }
}
else
{
    Print '<script>alert("Incorrect username!");</script>'; // Prompts the user
    Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
?>

<head>

    <title>My first PHP website</title>

</head>

<body>

    <h2>Login Page</h2>

    <a href="index.php">Click here to go back</a><br/><br/>

    <form action="checklogin.php" method="post">

        Enter Username: <input type="text" name="username" required="required"/> <br/>

        Enter Password: <input type="password" name="password" required="required" /> <br/>

        <input type="submit" value="Login"/>

    </form>

</body>

this is the code I have which should check the login and direct you to the index.php page but it doesn't do anything. all my user names and passwords are stored in my db The last bit of code is what it used to create the login page , I'm not sure what is stopping the login taking place? all the users are stored in the db properly but when I log in with them the page just refreshers quickly and does nothing

  • You don't need to check `$password == $table_password` twice :) Add a `print` statement to your `if($password == $table_password)` block just to make sure it's being executed. – PsychoMantis Feb 06 '17 at 17:39
  • Personally, I think you're wasting your time with this, since it is an unsafe piece of code. If this is for educational purposes, then it's your job to find out why it's not working. There are methods to use in order to check if code failed. – Funk Forty Niner Feb 06 '17 at 17:46
  • I'm trying to create a website linked to a stock database for a project at university – James Morris Feb 06 '17 at 17:49
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Feb 06 '17 at 17:54
  • ***Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).*** [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Feb 06 '17 at 17:54
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Feb 06 '17 at 17:54
  • Ive only been taught certain things and we have to use them. they don't update you on things when they change, they get stuck with old code – James Morris Feb 06 '17 at 18:04

1 Answers1

0

To expand on my comment regarding using a print statement to ensure your code is being executed and not requiring to check the user password twice, see the following changes below:

<?php
    session_start();
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);
    $bool = true;

    mysql_connect("localhost", "root", "") or die (mysql_error()); //Connect to server
    mysql_select_db("first_db") or die ("Cannot connect to database"); //Connect to database
    $query = mysql_query("Select * from users WHERE username='$username'"); // Query the users table
    $exists = mysql_num_rows($query); //Checks if username exists
    $table_users = "":
    $table_password = "";

    if($exists > 0) //IF there are no returning rows or no existing username
    {
        while($row = mysql_fetch_assoc($query)) // display all rows from query
        {
            $table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
            $table_password = $row['password']; // the first password row is passed on to $table_password, and so on until the query is finished
        }

        if($password == $table_password) //check password match
        {
            Print 'password matched';
            $_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
            header("location: home.php"); // redirects the user to the authenticated home page
        }
        else
        {
            Print '<script>alert("Incorrect Password!");</script>'; // Prompts the user
            Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
        }
    }
    else //user doesnt exist and/or no rows returned
    {
        Print '<script>alert("Incorrect username!");</script>'; // Prompts the user
        Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
    }
?>

Note that I've removed:

if(($username == $table_users) && ($password == $table_password))

because that line will never get executed if there is no username match found via the SQL query and if there is a match, the password would be compared on the next if-statement anyway.

I've added the Print statement to the if($password == $table_password) //check password match code block so you can see whether or not this section of code is actually being executed. If it is, then the header() is not redirecting, if not then your problem lies elsewhere.

Finally, as mentioned in the comments, this is some unsafe code vulnerable to SQL injection. You should consider using PDO or prepared statements with MySQLi. Your current solution is adequate for university, but in the real world it's another vulnerability. On that note, also disclosing whether a username or password is incorrect is a security risk and you should simply opt for 'invalid login' instead :)

PsychoMantis
  • 993
  • 2
  • 13
  • 29
  • Thanks for the advice. For some reason when I click login it still does nothing so I not sure where the problem lies. – James Morris Feb 06 '17 at 18:01
  • @JamesMorris did you try the code above? I've just edited it as I forgot to remove an `else` clause, try it again. Do you get any output at all? Does the form send to the right page? I suspect if you tried the code before I edited it and you had no output, you have error reporting disabled in your php.ini configuration file. If you can't edit the php.ini file directly, you should add `error_reporting(E_ALL);` to the top of your scripts to output any errors; it'll make debugging possible. – PsychoMantis Feb 06 '17 at 20:46
  • I got it working, it does sent it to the right page. I understand where I was going wrong so thank you for the help! – James Morris Feb 06 '17 at 22:47