|
| 1 | +<?php |
| 2 | +session_start(); |
| 3 | + |
| 4 | +$dsn = 'mysql:host=your_host;dbname=your_database'; |
| 5 | +$username = 'your_username'; |
| 6 | +$password = 'your_password'; |
| 7 | + |
| 8 | +try { |
| 9 | + $pdo = new PDO($dsn, $username, $password); |
| 10 | + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); |
| 11 | +} catch (PDOException $e) { |
| 12 | + die("Database connection failed: " . $e->getMessage()); |
| 13 | +} |
| 14 | + |
| 15 | +if ($_SERVER['REQUEST_METHOD'] === 'POST') { |
| 16 | + $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username"); |
| 17 | + $stmt->execute([':username' => $_POST['username']]); |
| 18 | + $user = $stmt->fetch(PDO::FETCH_ASSOC); |
| 19 | + |
| 20 | + if ($user && password_verify($_POST['password'], $user['password'])) { |
| 21 | + $_SESSION['user'] = $user['username']; |
| 22 | + $_SESSION['role'] = $user['role']; |
| 23 | + header("Location: index.php"); |
| 24 | + exit; |
| 25 | + } else { |
| 26 | + $error = "Invalid username or password."; |
| 27 | + } |
| 28 | +} |
| 29 | +?> |
| 30 | + |
| 31 | +<!DOCTYPE html> |
| 32 | +<html lang="en"> |
| 33 | +<head> |
| 34 | + <meta charset="UTF-8"> |
| 35 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 36 | + <title>Login</title> |
| 37 | +</head> |
| 38 | +<body> |
| 39 | + <h1>Login</h1> |
| 40 | + <?php if (isset($error)): ?> |
| 41 | + <p style="color: red;"><?= htmlspecialchars($error) ?></p> |
| 42 | + <?php endif; ?> |
| 43 | + <form method="post"> |
| 44 | + <label for="username">Username:</label> |
| 45 | + <input type="text" name="username" id="username" required> |
| 46 | + <br> |
| 47 | + <label for="password">Password:</label> |
| 48 | + <input type="password" name="password" id="password" required> |
| 49 | + <br> |
| 50 | + <button type="submit">Login</button> |
| 51 | + </form> |
| 52 | +</body> |
| 53 | +</html> |
0 commit comments