How do I handle user authentication

User authentication is a vital component of modern web applications. It ensures that users can securely log in and access protected resources. In this example, we'll explore a simple way to handle user authentication using PHP.
user authentication, secure login, PHP authentication, web application security
<?php session_start(); // Dummy user data for example purpose $users = [ 'user1' => 'password1', 'user2' => 'password2' ]; // Check if the login form has been submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username']; $password = $_POST['password']; // Authenticate user if (isset($users[$username]) && $users[$username] === $password) { $_SESSION['username'] = $username; echo "Login successful! Welcome, " . htmlspecialchars($username) . "."; } else { echo "Invalid username or password."; } } ?> <form method="post"> <label for="username">Username:</label> <input type="text" name="username" required> <br> <label for="password">Password:</label> <input type="password" name="password" required> <br> <input type="submit" value="Login"> </form>

user authentication secure login PHP authentication web application security