I tried to make an easy login in my university task, but faced on with some troubles.
When I press the button all works fine including request, but redirect doesn’t work at all, I tried to use js instead, but even then it works so bad, one time works, and another doesn’t an don’t really understand why I didn’t find the solution.
PHP code:
<?php
ob_start();
include("index.html");
include("db_connection.php");
$select_users = "SELECT * FROM users";
try {
$result = mysqli_query($conn, $select_users);
} catch (mysqli_sql_exception) {
die("FAILED TO FETCH USERS");
}
function generate_insert_user($username, $pass)
{
$hash = password_hash($pass, PASSWORD_DEFAULT);
$insert_user = "INSERT INTO users (username, pass_hash) VALUES ('$username', '$hash');";
return $insert_user;
}
if (isset($_POST['login'])) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
if (
$row['username'] == trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS))
&& password_verify($_POST['password'], $row['pass_hash'])
) {
header('Location: positions.php');
exit();
} else {
unset($_POST['username']);
unset($_POST['password']);
die("FAILED TO LOGIN");
}
}
}
}
if (isset($_POST['register'])) {
if (is_string($_POST['username']) && is_string($_POST['password'])) {
if (mysqli_num_rows($result) > 0) {
$existed = false;
while ($row = mysqli_fetch_assoc($result)) {
if (
$row['username'] == trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS))
) {
$existed = true;
}
}
if (!$existed) {
$query = generate_insert_user(trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS)), trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_SPECIAL_CHARS)));
try {
mysqli_query($conn, $query);
header('Location: positions.php');
exit();
} catch (mysqli_sql_exception) {
die("FAILED TO REGISTER");
}
} else {
die("SUCH USER ALREADY EXIST");
}
}
}
}
mysqli_close($conn);
ob_end_flush();