So I have a file called register.php and one called login.php, both use
passwordhash($pasw, DEFAULT_PASSWORD)
, register.php to create the hash and put it in the database, and login.php to see if the password hash of the user input matches the database entry.
register.php:
/*db info above */
$conn = new mysqli($servername, $username, $password, $dbname);
$user = $_POST['user'];
$pasw = $_POST['pasw'];
if($user !== mysqli_real_escape_string($conn, $user) || ctype_alnum($user) !== true) {
$_SESSION['errormsg'] .= "<script>alert('Invalid Username, Must be alphanumerical')</script>";
$error = 1;
}
if(strlen($pasw) >= 16 || strlen($pasw) < 4) {
$_SESSION['errormsg'] .= "<script>alert('Invalid Username, must be more than 4 and less than 16 characters long')</script>";
$error = 1;
}
if(strlen($pasw) < 8 ) {
$_SESSION['errormsg'] .= "<script>alert('Invalid Password, Must be AT LEAST 8 characters')</script>";
$error = 1;
}
if($error === 1) {
Header('Location: index.php');
exit();
}
$pasw = password_hash($pasw, PASSWORD_DEFAULT);
$curtime = time();
$userip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO userdata (user, password, timestamp, IP) values ('$user', '$pasw', '$curtime', '$userip')";
if (mysqli_query($conn, $sql)){
$_SESSION['name'] = $user;
if($user === 'Admin') {
$_SESSION['admin'] = 'yes';
}
Header('Location: index.php');
exit();
}
else {
$_SESSION['errormsg'] = "<script>alert('Unknown Error')</script>";
Header('Location: index.php');
}
and login.php:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = mysqli_real_escape_string($conn, $_POST['user']);
$pasw = $_POST['pasw'];
$paswhash = password_hash($_POST['pasw'], PASSWORD_DEFAULT);
$result = mysqli_query($conn, "SELECT * FROM userdata where user = '$name' and password = '$paswhash'");
var_dump($result);
if(mysqli_num_rows($result) > 0) {
$_SESSION['name'] = $name;
Header('Location: index.php');
}
else {
$_SESSION['errormsg'] = "<script>alert('Invalid user/pass combo" . $name . " " . $paswhash . "')</script>";
//displaying name and password hash for debugging reasons
Header('Location: index.php');
}
The data from register.php gets written in the database just fine, But when I enter the unhashed password in the input field they don't match, and the error message states that the password becomes another hash.
Am i doing something terribly wrong?