How can existing systems be modified to incorporate a login feature in PHP?
To incorporate a login feature into an existing system in PHP, you can create a login form that collects user credentials, validate them against a database of users, and set a session variable upon successful login. This session variable can then be used to restrict access to certain parts of the system that require authentication.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
// Validate username and password against database
if ($username == 'admin' && $password == 'password123') {
$_SESSION['logged_in'] = true;
header('Location: dashboard.php');
exit();
} else {
$error = "Invalid username or password";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post" action="">
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<button type="submit">Login</button>
</form>
<?php if(isset($error)) { echo $error; } ?>
</body>
</html>