PHP
Build a simple login system
17 views
Code
/login-system
│
├── index.php ← Login form
├── dashboard.php ← Logged-in page
├── logout.php ← Logout handler
├── users.txt ← Stores user credentials
└── style.css ← Optional: CSS styling
1. users.txt (sample users)
admin:admin123
rohan:pass456
2. index.php
php
Copy
Edit
<?php
session_start();
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$lines = file('users.txt', FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
list($user, $pass) = explode(':', trim($line));
if ($user == $username && $pass == $password) {
$_SESSION['username'] = $username;
header("Location: dashboard.php");
exit();
}
}
$error = "Invalid username or password.";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2>Login</h2>
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" required><br><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
<p style="color:red;"><?php echo $error; ?></p>
</body>
</html>
3. dashboard.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h2>Welcome, <?php echo $_SESSION['username']; ?>!</h2>
<p>This is your dashboard.</p>
<a href="logout.php">Logout</a>
</body>
</html>
4. logout.php
<?php
session_start();
session_destroy();
header("Location: index.php");
exit();
5. (Optional) style.css
body {
font-family: Arial, sans-serif;
margin: 50px;
}
input, button {
padding: 8px;
width: 200px;
}
Explanation
Here's a simple login system using HTML, CSS, and PHP with file-based user authentication (no database). This version is for educational/demo use only – real-world applications should use password hashing and database storage.
Rate this snippet
Related Snippets
Have a Better Solution?
Know a more efficient way to solve this problem? Share your own code snippet and help the community!
Submit Your Version