How can PHP be used to implement a simple login system without a database?
To implement a simple login system without a database, you can store user credentials in an associative array within your PHP code. When a user attempts to log in, you can compare the provided username and password with the values stored in the array. If they match, you can set a session variable to indicate that the user is logged in.
<?php
// User credentials stored in an associative array
$users = [
'username' => 'password'
];
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($users[$username]) && $users[$username] === $password) {
$_SESSION['logged_in'] = true;
echo 'Login successful!';
} else {
echo 'Invalid username or password';
}
}
?>
<form method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>