-2

Creating a user saves the info into the database, but when I try to sign it just automatically signs in, whether the information was stored in the database or not. Please help.

This is my server.php code i think the issue lies in here but im not sure.

<?php 
session_start();
// initializing variables
$username = "";
$email    = "";
$errors = array(); 
// connect to the database
$db = mysqli_connect('localhost', 'dbuser', 'dbpassword', 'dbname');


// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
    array_push($errors, "The two passwords do not match");
  }

  // first check the database to make sure 
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM loginsystem WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);

  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database

    $query = "INSERT INTO loginsystem (username, email, password) 
              VALUES('$username', '$email', '$password')";
    mysqli_query($db, $query);
    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now logged in";
    header('location: home.php');
  }
}

// ... 
// ... 
// LOGIN USER
if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password_1']);

  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);


      $_SESSION['username'] = $username;
      $_SESSION['success'] = "You are now logged in";
      header('location: home.php');
    }else {
        array_push($errors, "Wrong username/password combination");
    }
  }


?>

With my login.php being

<?php include('includes/server.php') ?>
<!DOCTYPE html>
<html>
<head>
  <title>Clout-Cloud | LOGIN</title>
  <link rel="stylesheet" type="text/css" href="css/style3.css">
</head>
<body>
<div class="container">
    <section id="content">
            <h1>CloutCloud Login</h1>
            <div>
    <form method="POST" action="login.php">
    <div class="input-group">
        <div class="input-group">
      <label>Username</label>
      <input type="text" name="username"  required>
    </div>
    <div class="input-group">
      <label>Password</label>
      <input type="password" name="password_1" required>
    </div>
    <div class="input-group">
      <button type="submit" class="button" name="login_user">Login</button>
    </div>
    <p>
    <a href="recoverpassword.php">Lost your password?</a>
                <a href="register.php">Register</a>
            </div>
            </div>
            </div>
        </form><!-- form -->
    </div>
    </section><!-- content -->
</div><!-- container -->
</body>

I dont see where im really going wrong, but there is an issue. Please help me resolve.

Update I've tried getting results from my dabatase using the code

$password = md5($password);
    $query = "INSERT INTO loginsyle (username, password) 
                      VALUES('$username', $password')";
while($row = mysqli_fetch_assoc($result)) {
   $username = $row['username'];
   $password = $row['password']; 

}
    }else {
        array_push($errors, "Wrong username/password combination");
    }

to try and get my results from my query. although i think part of this has fixed part of the issue of just being able to sign in with random info and without registry,but now im getting the errors

Notice: Undefined variable: result in /home/u572108555/public_html/includes/server.php on line 72

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in /home/u572108555/public_html/includes/server.php on line 72

what could be causing this? am i trying to grab the results from my query the wrong way?

Clout Cloud
  • 31
  • 1
  • 10
  • Please be aware that your code is **vulnerable** to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection). You should use [**prepared statements**](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) to prevent this. Also ensure that your database user only has the [**required privileges**](https://en.wikipedia.org/wiki/Principle_of_least_privilege). You can refer to [**this post**](http://stackoverflow.com/questions/60174) for further information on how to prevent SQL injection in PHP. Also, don't use `MD5` for password encryption - that's just asking for trouble :) – Obsidian Age May 25 '18 at 03:07
  • 1
    *Please help* is not a question, and *there is an issue* is not a problem description. And please stop SHOUTING when posting here. It',s difficult to parse text in ALL CAPS, it won't get you an answer any faster, and it's rude of you to come here and ask for *free help* by SHOUTING for attention. There are Shift keys on both sides of your keyboard to make them easy to reach and use, because properly cased text is easier to read. Please use them instead of your CAPS LOCK. – Ken White May 25 '18 at 03:08
  • i dont understand, i didnt use CAPS LOCK for anything ive posted? – Clout Cloud May 25 '18 at 03:16
  • @CloutCloud He is referring to your previous title.. – Romeo Sierra May 25 '18 at 03:17
  • oh ok sorry. new to the site. that wouldve been easier to say. – Clout Cloud May 25 '18 at 03:24

2 Answers2

0

You aren't validating the results of the query. You should check the number of results returned = 1, less than that (0) = user details dont match. more than that (2+) and you have an issues with overlapping login credentials or a bad query.

I'd also recommend against using MD5 as your encryption

as other have mentioned, you are vulnerable to SQL Injection, use strip slashes and escapes to combat this, like this

$myusername = stripslashes($myusername);
$myusername = mysqli_real_escape_string($myusername);

to find out the number of results you have you can use a function like this

$sql="SELECT * FROM $tbl_name WHERE ID='$myusername' and password= '$password'";  
$result=mysqli_query($sql);

// Mysqli_num_row is counting table row
$count=mysqli_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// user is logged in
}
James Lingham
  • 419
  • 1
  • 3
  • 17
  • what would the script for returning results from the query be if you dont mind? :) – Clout Cloud May 25 '18 at 03:12
  • I have updated my answer to provide an example, copied from an old script i did a few years ago, should hold up and give an idea of how to approach the problem for you. – James Lingham May 25 '18 at 03:17
  • @Mehdi because it used mysql_ instead of mysqli_ ? As i said in my comment, it's older code but should point him in the right direction of what he should be looking to do. – James Lingham May 25 '18 at 03:40
  • this didnt seem to work, im getting "Undefined variable: password" whenever i changed the escape strings to stripslashes – Clout Cloud May 25 '18 at 03:40
  • @JamesLingham writing old code in answers is in general a bad idea, your answer will be indexed and accessible via search engines for new readers (readers that probably won't care to read your comments). Take the time and write a proper code, even better if you encourage Parametrized queries using PDO or Mysqli. – Spoody May 25 '18 at 03:43
  • @Mehdi, You are right, I have updated the code to use mysqli – James Lingham May 25 '18 at 03:48
-1

You don't seem to validate the result of $results = mysqli_query($db, $query). Following is the code indicating what you need to do.

$results = mysqli_query($db, $query);
// Here you have to check the $result and see if you have one record selected.
// However you are not doing that currently.
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";

On a side note, the way you are doing this seems to have a multitude of flaws.

  1. One file named server.php has all routines. This will make you end up with one monolithic file, which is far from maintainability.
  2. Your SQL queries are vulnerable to SQL injections. Use prepared statements instead of what you are doing right now.
  3. MD5 is long known to have collisions hence abandoned a long time ago. Even SHA1 is known to be not so secure. Go for something like SHA256 or even better if it is BCrypt or Blowfish.
  4. When you validate login just don't validate the number of records in the result set. Instead, check if it has exactly one record, and the record values are matching.
Romeo Sierra
  • 1,666
  • 1
  • 17
  • 35