I am writing a login form and do some functions and code about if the password is validated it will redirect to dashboar file.
I chatgpt it but nothing is fix, I hope you help with this kind of problem and learn from it. I am also a beginner in php so bear with me. Thank you!
this is my code in index file
session_start();
include_once 'config/functions.php';
$email = $password = "";
$emailErr = $passwordErr = "";
if (isset($_POST['submit'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = $_POST['password'];
$validation_errors = validate_user_login($email, $password);
foreach ($validation_errors as $field => $error) {
${$field . 'Err'} = $error;
}
if (empty($validation_errors)) {
$result = login_user($email, $password);
if ($result === true) {
redirect('dashboard.php');
exit;
}
} else {
// echo 'something is wrong';
}
}
?>
this is my functions in function files
function login_user($email, $password) {
global $conn;
// Use prepared statement to prevent SQL injection
$query = "SELECT * FROM users WHERE email = ? LIMIT 1";
$stmt = mysqli_prepare($conn, $query);
if ($stmt) {
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
// Verify the password
if (password_verify($password, $row['password'])) {
// Password is correct
if ($row['user_type'] == 'users') {
session_start();
$_SESSION['fname'] = $row['fname'];
$_SESSION['user_id'] = $row['user_id'];
// Redirect to the dashboard
redirect('../dashboard.php');
} else {
return 'Invalid user type';
}
} else {
return 'Invalid email or password'; // Password is incorrect
}
} else {
return 'Invalid email or password'; // User not found
}
mysqli_stmt_close($stmt);
} else {
die("Error in statement preparation: " . mysqli_error($conn));
}
}
// Function to handle redirection
function redirect($url) {
header("Location: $url");
exit();
}
2
Answers
Unless you’re using some other php library, I’d suggest changing "redirect" to "header".
https://www.php.net/manual/en/function.header.php
If that fails, put the logic in a try / catch statement or other logic that allows you to print out the error to identify where it’s failing.
Most modern clients accept relative URIs as the " Location: argument, but some older clients require an absolute URI, including schema, hostname, and absolute path. So I recommend using the absolute path everywhere