Skip to content
PHP Logo

How can PHP be used to create a password-protected page on a website?

To create a password-protected page on a website using PHP, you can use a simple authentication system where users need to enter a password to access the page. This can be achieved by creating a login form that checks the entered password against a predefined password. If the passwords match, the user is granted access to the protected page.

php
<?php
// Define the correct password
$correct_password = "mypassword";

// Check if the form has been submitted
if(isset($_POST['password'])) {
    // Get the entered password
    $entered_password = $_POST['password'];

    // Check if the entered password matches the correct password
    if($entered_password == $correct_password) {
        // Password is correct, allow access to the protected page
        echo "Welcome to the protected page!";
    } else {
        // Password is incorrect, display an error message
        echo "Incorrect password. Please try again.";
    }
}
?>

<!-- Create a simple login form -->
<form method="post">
    <label for="password">Password:</label>
    <input type="password" name="password">
    <button type="submit">Submit</button>
</form>