How can a login function be created for a website using PHP?

To create a login function for a website using PHP, you need to validate the user's input (username and password) against a database of registered users. If the credentials match, you can set a session variable to indicate that the user is logged in. If the credentials do not match, you can display an error message.

<?php
session_start();

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate user input
    $username = $_POST["username"];
    $password = $_POST["password"];
    
    // Check if the username and password match a record in the database
    // Replace this with your own database connection and query
    if ($username == "admin" && $password == "password") {
        $_SESSION["loggedin"] = true;
        header("Location: dashboard.php");
        exit();
    } else {
        $error = "Invalid username or password";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <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>