Ive created a simple login script which works to an extent. All the validation is working correctly so if i enter the wrong username and password it shows me the error message Your username or password is wrong but when i enter the correct username and password it doesnt direct me to the users/index.php page and sort of just reloads the login page.
Here is my code -
<?php
session_start();
$errors = [];
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
if(!empty($_POST)) {
if(empty($username)) {
$errors[] = "Please enter a username";
echo "<style type=\"text/css\"> #username { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
}
if(empty($password)) {
$errors[] = "Please enter a password";
echo "<style type=\"text/css\"> #password { background-color:#F5A9A9;border:1px solid #DF0101; } </style>";
} else {
if(empty($errors)) {
$connect = new PDO('mysql:host=localhost;dbname=uacvideos;charset=utf8mb4', 'root', '');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(!$connect) {
header("Location:"); // ADD ERROR LINK
}
$salt = "Thisismysalt";
$hashedpass = hash('sha512', $password . $salt);
$result = $connect->query("SELECT COUNT(*) FROM users WHERE username = '$username' AND password = '$hashedpass'");
if($result->fetchColumn() > 0) {
$_SESSION['loggedin'] = 'true';
$_SESSION['username'] = $username;
header("Location: users/index.php"); // ADD LINK
} else {
$errors[] = "Your username or password is incorrect";
}
}
}
}
?>