here’s a simple example of login authentication using PHP and sessions. This example includes a form for logging in, a script to process the login, and a protected page that only logged-in users can access.
Step 1: Create a login form (login.php)
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="POST" action="authenticate.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Step 2: Create the authentication script (authenticate.php)
<?php
session_start();
// Dummy credentials for demonstration
$valid_username = "admin";
$valid_password = "password";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
// Simple authentication check
if ($username == $valid_username && $password == $valid_password) {
// Set session variables
$_SESSION["username"] = $username;
$_SESSION["loggedin"] = true;
// Redirect to the protected page
header("Location: protected.php");
exit;
} else {
echo "Invalid username or password";
}
}
?>
Step 3: Create a protected page (protected.php)
<?php
session_start();
// Check if the user is logged in
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
// Redirect to login page
header("Location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Protected Page</title>
</head>
<body>
<h2>Welcome, <?php echo $_SESSION["username"]; ?>!</h2>
<p>This is a protected page.</p>
<a href="logout.php">Logout</a>
</body>
</html>