How can .htpasswd be used to implement a login window for a PHP website?
To implement a login window for a PHP website using .htpasswd, you can create a .htpasswd file with encrypted username and password pairs. Then, use PHP to prompt users for their credentials and validate them against the .htpasswd file. If the credentials match, grant access to the protected content.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$htpasswd_file = '.htpasswd';
$htpasswd_contents = file_get_contents($htpasswd_file);
$htpasswd_lines = explode("\n", $htpasswd_contents);
foreach ($htpasswd_lines as $line) {
list($stored_username, $stored_password) = explode(':', $line);
if ($username == $stored_username && password_verify($password, $stored_password)) {
// Successful login
echo 'Welcome, ' . $username . '!';
exit;
}
}
// Invalid credentials
echo 'Invalid username or password.';
}
?>
<form method="post">
<input type="text" name="username" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Login</button>
</form>
Related Questions
- What are some tips for configuring SQL database access in PHP scripts when switching hosting providers?
- In what ways does the EVA principle (Einheit von Verantwortlichkeit und Abhängigkeit) in PHP development help prevent errors related to headers being sent prematurely, and how can developers adhere to this principle effectively?
- What best practices should be followed when working with zip files in PHP, especially in terms of file extraction?