359
<?php
session_start(); // Start the session
// Check if the user is already logged in, if yes, redirect to dashboard
if (isset($_SESSION["SESS_USER_ID"])) {
header("Location: dashboard.php");
exit;
}
// Include database connection or any necessary files
$msg_danger = ''; // Initialize error message variable
// Define login function
function login()
{
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['token_']) && hash_equals($_SESSION['token_'], $_POST['token_'])) {
// Validate email and password
$email = trim($_POST['email_']);
$password = $_POST['Password_'];
// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return "Invalid email format";
}
// Validate password length or complexity
// Hash and compare password (ensure to properly hash passwords in your database)
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Check database for user credentials
// Replace this with your database query logic
$user_id = 1; // Assuming 1 is the ID of the admin user
if ($user_id) {
// Set session variables
$_SESSION['SESS_USER_ID'] = $user_id;
$_SESSION['SESS_FIRST_NAME'] = "Admin";
// Redirect to dashboard
header('Location: dashboard.php');
exit();
} else {
return "Invalid email address or password";
}
} else {
return "Invalid request";
}
}
}
// Call the login function
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$msg_danger = login();
}
// Generate CSRF token and store it in session
if (!isset($_SESSION['token_'])) {
$_SESSION['token_'] = bin2hex(random_bytes(32));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<?php if (!empty($msg_danger)) : ?>
<p style="color: red;"><?php echo htmlspecialchars($msg_danger); ?></p>
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="hidden" name="token_" value="<?php echo htmlspecialchars($_SESSION['token_']); ?>">
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email_" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="Password_" required>
</div>
<button type="submit">Login</button>
</form>
</body>
</html>
This code implements the following features:
password_hash() function.htmlspecialchars() to prevent XSS attacks.FILTER_VALIDATE_EMAIL.