-2

For weird reasons my php connection does not forward to the other page, instead it stays on the connection and blank page im so confused. I want it to work where if correct password it goes to the members page and if it wrong then of course it would return an error message.

<?php
    $error='';
    if(isset($_POST['submit'])) {
        if(empty($_POST['username']) || empty($_POST['password'])) {
            $error = "Username or Password is invalid!";
        } else {
            $username = $_POST['username'];
            $password = $_POST['password'];
            
            $conn = mysqli_connect("localhost", "root", "");
            $db = mysqli_select_db($conn, "insanegalaxy");
            $query = mysqli_query($conn, "SELECT * FROM members WHERE password='$password' AND username='$username'");
            
            $rows = mysqli_num_rows($query);
            if($rows == 1) {
                header("Location: ../members/index.php");
            } else {
                $error = "Username or Password is invalid!";
            }
            mysqli_close($conn);
        }
    }
    
?>
Johannes
  • 64,305
  • 18
  • 73
  • 130
  • Maybe you should echo `$error` somewhere... – Louys Patrice Bessette Nov 07 '20 at 01:50
  • Can you provide directory structure of your project? – gobliggg Nov 07 '20 at 01:51
  • 1
    Please read about **[SQL injection](https://en.wikipedia.org/wiki/SQL_injection)**. Instead of building queries with string concatenation, use **[prepared statements](https://secure.php.net/manual/en/pdo.prepare.php)** with **[bound parameters](https://secure.php.net/manual/en/pdostatement.bindparam.php)**. See **[this page](https://phptherightway.com/#databases)** and **[this post](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)** for some good examples. – John Conde Nov 07 '20 at 02:52
  • 1
    You don't know what's wrong because you don't check for errors in your code. Never assume the code is always going to work flawlessly. Use [`mysqli_error()`](http://php.net/manual/en/mysqli.error.php) to get a detailed error message from the database. – John Conde Nov 07 '20 at 02:52
  • 1
    **Never store plain text passwords!** Please use [PHP's built-in functions](//php.net/manual/en/function.password-hash.php) 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) (and you should consider upgrading to a supported version of PHP). Make sure you [don't escape passwords](//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. – John Conde Nov 07 '20 at 02:52
  • ok, im new to php so it i guess good feedback :| – LurkingPsycho Nov 07 '20 at 03:17

2 Answers2

0

In your $conn variable for the database connection you are only including the server and username, but not the database name. Then you have a $db variable which obviously contains the database name (and the $conn variable), but you don't use that anywhere later on. Instead you use the $conn variable (i.e. without the database name) with the mysql statement...

Johannes
  • 64,305
  • 18
  • 73
  • 130
  • Do u mean this? $db = mysqli_select_db($conn, "insanegalaxy"); – gobliggg Nov 07 '20 at 01:55
  • why select the database in the second command VS just passing the db name as the third argument as defined in the docs? https://www.php.net/manual/en/function.mysqli-connect.php – andersryanc Nov 07 '20 at 02:01
0

Precursor

@John Conde has highlighted a bunch of problems with your code already:

  • Your code is susceptible to SQL Injection. You shouldn't be passing user input straight into a query string. Malicious behaviour and accidents happen and could corrupt, expose, or otherwise negatively effect your stored data.
  • It doesn't look as though you've checked the error logs: enabling error reporting and checking the logs can you give the best idea of whether your logic is wrong or there is an error with your code.
  • You really shouldn't be storing passwords in plain text form! PHP has built in function to hash and verify passwords, please use them!!

There are however, a couple of additional things:

  • Your code doesn't output anything UNLESS it succeeds (i.e. it redirects to a different page)
    • In the event that any of your error conditions are met (e.g. username is empty) the page will load as a blank page -- which seems to be what you describe!
    • You set $error but you never output it to the page. So you don't know if anything was added to it!
      • Add echo "Error: {$error}"; just above ?> and see what happens

Fixing it

Your code

session_start();        // Begin/continue the users session (this is how we monitor if they are logged on or not!)

// Database credentials
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "insanegalaxy";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);       // Set error reporting parameters
$mysqli   = new mysqli($db_host, $db_user, $db_pass, $db_name);  // Make mysqli connection

$error = "";

do{
// Using a "do...while(...)" loop means we can break out of it if error
// conditions are met and have no need for a series of nested if statements

    // Check if user is already logged on
    // If not then break the loop with an error
    if($_SESSION["loggedon"]){
        $error = "You're already logged on!";
        break;
    }

    // Check something was actually submitted
    // If not then break the loop with an error
    if(!isset($_POST["submit"])){
        $error = "Nothing submitted!";
        break;
    }

    // Check something was submitted for username and password
    // If not then break the loop with an error
    if(empty($_POST["username"]) || empty($_POST["password"])){
        $error = "Username or Password is invalid!";
        break;
    }


    $username = $_POST["username"];  // Set username variable
    $password = $_POST["password"];  // Set password variable


    // SELECT query to get the user id (assumed name of column) and password for verification
    // ? is used as a place holder for the variable we'll bind to it later
    $sql   = "SELECT userid, password FROM members WHERE username = ?";  


    $query = $mysqli->prepare($sql);             // Prepare the query
    $query->bind_param("s", $username);          // Bind $username to the query; "s" sets data type to string
    $query->execute();                           // Run the query
    $query->store_result();                      // Store the result
    $query->bind_result($userid, $db_password);  // Bind the result

    // Check that results were returned (i.e. the user exists)
    // If not then break the loop with an error
    if(!$query->num_rows){
        $error = "User doesn't exist!";
        break;
    }

    // Check that the password entered matches the stored one
    // If not then break the loop with an error
    if(!password_verify($password, $db_password)){
        $error = "Username or Password is invalid!";
        break;
    }

    $_SESSION["userid"]   = $userid;           // Set SESSION variable for users id
    $_SESSION["loggedon"] = TRUE;              // Set SESSION variable to denote the user is logged on
    header("Location: ../members/index.php");  // Redirect to the correct web page
    exit;                                      // Exit without outputting anything else

}
while(FALSE);

// Code to be carried out IF an error occurred...
echo "Error: {$error}";

When creating a user...

To hash the passwords on creating a new user you can use this line:

 $password = password_hash($password, PASSWORD_DEFAULT);
Steven
  • 6,053
  • 2
  • 16
  • 28