How can PHP be used to create a login page that restricts access to specific users?
To create a login page that restricts access to specific users, you can use PHP to validate user credentials against a database of authorized users. Upon successful login, you can set a session variable to track the user's authentication status and restrict access to certain pages based on this variable.
<?php
session_start();
// Check if the user is already logged in
if(isset($_SESSION['username'])) {
header("Location: dashboard.php");
exit();
}
// Check if the form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = "admin";
$password = "password";
// Validate user credentials
if($_POST['username'] == $username && $_POST['password'] == $password) {
$_SESSION['username'] = $username;
header("Location: dashboard.php");
exit();
} else {
echo "Invalid username or password";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form method="POST" action="">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>