What are some best practices for implementing a user authentication system in PHP for a time tracking application?
Issue: Implementing a user authentication system in PHP for a time tracking application is crucial to ensure that only authorized users can access the application and its features securely. Code snippet:
<?php
session_start();
// Check if the user is already logged in
if(isset($_SESSION['user_id'])){
// Redirect to the dashboard or homepage
header("Location: dashboard.php");
exit;
}
// Check if the form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate the login credentials
$username = $_POST['username'];
$password = $_POST['password'];
// Check the credentials against the database
if($username === 'admin' && $password === 'password'){
// Set the user session
$_SESSION['user_id'] = 1;
// Redirect to the dashboard or homepage
header("Location: dashboard.php");
exit;
} else {
// Display an error message
$error = "Invalid username or password";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form method="post" action="">
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<button type="submit">Login</button>
</form>
<?php if(isset($error)){ echo $error; } ?>
</body>
</html>
Keywords
Related Questions
- Should PHP code be saved in a PHP file or an HTML file?
- In the context of PHP development for browser games, what are the implications of using open-source code like FreeGW and how can potential issues be addressed?
- Is it necessary to use PHP to align buttons within a table, or can it be achieved solely with HTML?