What are some alternatives to using .htaccess for password protection in PHP websites?

Using PHP to handle password protection in websites can be a more flexible alternative to using .htaccess files. By implementing password protection in PHP, you can have more control over user authentication, session management, and customization of the login process.

<?php
session_start();

$valid_username = 'admin';
$valid_password = 'password123';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    if ($username == $valid_username && $password == $valid_password) {
        $_SESSION['authenticated'] = true;
        header('Location: protected_page.php');
        exit;
    } else {
        echo 'Invalid username or password';
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <form method="post" action="">
        <input type="text" name="username" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <button type="submit">Login</button>
    </form>
</body>
</html>