2

I got this code from an online source and it was working fine but when I tried using today it logs the user into the website but doesn't insert anything into the table. So if I log out of the newly created account then try to sign in it wont work.

My data connection page is server.php. register page is register.php

I looked over for self error. I even re copied the code from online into it and replaced with data connection info and still doing the same thing.I thought maybe it was my server.php but all the user accounts in the table still work so it isn't the server.pgp page.

Register.php

<!DOCTYPE html>
<html>
<head>
  <title>Registration system PHP and MySQL</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="header">
    <h2>Register</h2>
  </div>

  <form method="post" action="register.php">
    <?php include('errors.php'); ?>
    <div class="input-group">
      <label>Username</label>
      <input type="text" name="username" value="<?php echo $username; ?>">
    </div>
    <div class="input-group">
      <label>Email</label>
      <input type="email" name="email" value="<?php echo $email; ?>">
    </div>
    <div class="input-group">
      <label>Password</label>
      <input type="password" name="password_1">
    </div>
    <div class="input-group">
      <label>Confirm password</label>
      <input type="password" name="password_2">
    </div>
    <div class="input-group">
      <button type="submit" class="btn" name="reg_user">Register</button>
    </div>
    <p>
        Already a member? <a href="login.php">Sign in</a>
    </p>
  </form>
</body>
</html>

Server.php


// initializing variables
$username = "";
$email    = "";
$errors = array(); 

// connect to the database

$db = mysqli_connect(REMOVED FOR PUBLIC VIEWING);

// 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_1']);
  $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 users 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 users (username, email, password) 
              VALUES('$username', '$email', '$password')";
    mysqli_query($db, $query);
    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now logged in";
    header('location: index.php');
  }
}

This should result in the user being created and logged in automatically which is what it does. It doesn't insert into the database like it should.Should insert

id Username Email Encrypted Password

Cody O'Meara
  • 55
  • 10
  • 2
    **Warning!** Don't use `md5()` for password hashing. MD5 is not only super fast (which is bad), but hash collisions have been found (which also is bad). Use PHP's [password_hash()](https://www.php.net/manual/en/function.password-hash.php) to get a secure hash and use [password_verify()](https://www.php.net/manual/en/function.password-hash.php) to validate a password against a hash. – M. Eriksson May 21 '19 at 15:22
  • 2
    You should also look into using [parameterized prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of manually escaping the user data and build your queries like that. – M. Eriksson May 21 '19 at 15:24
  • 2
    Considering the above issues, I'm guessing that the online resource you found is either out of date or generally insecure. Remember that you ask people to give you their credentials (and we all know how people love to reuse the same credentials everywhere) so it's up to you to keep their data as secure as possible. – M. Eriksson May 21 '19 at 15:26
  • @MagnusEriksson Thanks for the info. When I get this working, I will switch to password_hash – Cody O'Meara May 21 '19 at 15:29
  • 2
    That will require you to rewrite parts of the code (since I'm assuming you will start using prepared statements as well?) so I would recommend that you start with that. Debugging code before you rewrite it seems like a waste of time. You might even solve your issue when rewriting it... – M. Eriksson May 21 '19 at 15:30
  • 2
    [link]http://codewithawa.com/posts/complete-user-registration-system-using-php-and-mysql-database How about that! What a coinsidence! I just looked through the comments and see you at the bottom saying how insecure it is from a year ago, HA! @MagnusEriksson – Cody O'Meara May 21 '19 at 15:33
  • 1
    Hehe, I remember that post :-) It's riddled with security issues. Make sure to read the comments as well when you find some code online. ;-) You should also go through the code to understand what it actually does, do some research for best practices etc. Using "random" code from internet without understanding what it does you can set yourself up for some _major_ security issues. – M. Eriksson May 21 '19 at 15:38

2 Answers2

0

From the code posted, it looks like the form in register.php is posting to itself, not to server.php.

Maybe change

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

to

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

[Aside, definitely consider the comments made by @magnus-eriksson, which aren't directly related to the question, but are very relevant]

Chris Lear
  • 6,592
  • 1
  • 18
  • 26
  • Tried adding that to register.php and it resulted in the same thing. It processed the data continuing to the main page but didn't insert into the table. – Cody O'Meara May 21 '19 at 15:27
  • You could change `mysqli_query($db, $query);` to `if (!mysqli_query($db, $query)) { echo("Error description: " . mysqli_error($db)); }` – Chris Lear May 21 '19 at 15:33
  • Generally, add some more debugging - use `echo` to show you the values of variables and `die` as a simple way of being able to see what's going on before the redirect happens – Chris Lear May 21 '19 at 15:34
  • @ChrisLear I would recommend `var_dump()` over `echo`, since that can handle objects and arrays as well (and will show the proper value of booleans) – M. Eriksson May 21 '19 at 15:36
  • 1
    @MagnusEriksson I agree. I was trying to keep things simple, but perhaps I overdid it – Chris Lear May 21 '19 at 15:37
0

Server.php

Check if you actually don't have any errors in $error
and what are errors when inserting by mysqli

an example how to do that:

<?php

// initializing variables
$username = "";
$email    = "";
$errors = array(); 

// connect to the database

$db = mysqli_connect('REMOVED FOR PUBLIC VIEWING');

// 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_1']);
  $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 users 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");
    }
  }

echo "\nThere should be no errors here\n";
var_dump($errors);

if (count($errors)) {
    die('There ware errors!');
}

  // 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 users (username, email, password) 
              VALUES('$username', '$email', '$password')";

    if(!mysqli_query($db, $query)) {
        die("Mysqli error: " . mysqli_error($db));
    }



    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now logged in";
    header('location: index.php');

  }
}

Once you got it working:
read about PDO and MySQL injection and rewrite your mysql code by using PDO

Jimmix
  • 5,644
  • 6
  • 44
  • 71
  • 2
    _"and rewrite your mysql code by using PDO"_ - Why would they need to do that? – M. Eriksson May 21 '19 at 15:33
  • @MagnusEriksson PDO in 2019 is in general more recommended to use than mysql/mysqli. Some read about [PDO and MySQL injection](https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection) and [PDO Tutorial](https://phpdelusions.net/pdo) no real reason to stick to mysql/mysqli nowadays unless PDO is not available at your PHP (I doubt) – Jimmix May 21 '19 at 15:47
  • You're talking about SQL injections (which are library agnostic). However, if you use parameterized prepared statements, mysqli is just as safe as PDO. Personally, yes, I prefer PDO but since the OP is already using mysqli, there's no reason to rewrite all the database code. Btw, you know that the link doesn't say anything about using PDO over mysqli, right? It explains that you might be vulnerable for SQL injections even with PDO and prepared statements (if you have some edge case configuration). – M. Eriksson May 21 '19 at 15:57