How can PHP developers ensure the security of password-protected pages without using a database?
To ensure the security of password-protected pages without using a database, PHP developers can store hashed passwords in a PHP file and compare user input against these hashed passwords. This method eliminates the need for a database and still provides a level of security for password protection.
<?php
$passwords = array(
'admin' => '$2y$10$uFh9JpO/yTl1s7mzVlZ9cOzT9Fk4tYz2bX8GzBdRiZ7wZ8Dg1qo5u', // hashed password for user 'admin'
'user' => '$2y$10$4wVj5V3GJ3m8lFJ4gD4z3u7J9Ck2fEJ6fF7tJ9H8fS6gT4G0hJ4jK', // hashed password for user 'user'
);
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(array_key_exists($username, $passwords) && password_verify($password, $passwords[$username])) {
echo "Welcome, $username!";
} else {
echo "Invalid username or password.";
}
}
?>
Related Questions
- Are there best practices for handling code formatting, such as using <pre> tags, when displaying text with preserved spacing in PHP?
- How can the "undefined function" error be resolved when trying to include and call a function in PHP?
- What security considerations should PHP developers keep in mind when handling user input in their scripts?