How can PHP be used to validate user credentials before redirecting to a secure page?

To validate user credentials before redirecting to a secure page, you can create a PHP script that checks the entered username and password against a database of valid credentials. If the credentials are correct, the script can redirect the user to the secure page. If the credentials are incorrect, the script can display an error message.

<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validate user credentials (this is a simple example, in a real application, you would query a database)
    if ($username === 'admin' && $password === 'password') {
        // Redirect to the secure page
        header("Location: secure_page.php");
        exit();
    } else {
        // Display an error message
        echo "Invalid username or password";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required><br><br>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>