register.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. session_start();
  3. if (isset($_SESSION['user_id'])) {
  4. header('Location: index.php');
  5. exit;
  6. }
  7. $pdo = new PDO('mysql:host=sql101.infinityfree.com;dbname=if0_39567875_nex', 'if0_39567875', 'PIvOR9WViHm'); // Update credentials
  8. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  9. $username = $_POST['username'];
  10. $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
  11. if (isset($_POST['register'])) {
  12. // Register
  13. $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
  14. if ($stmt->execute([$username, $password])) {
  15. $_SESSION['user_id'] = $pdo->lastInsertId();
  16. header('Location: index.php');
  17. } else {
  18. echo "Username taken.";
  19. }
  20. } elseif (isset($_POST['login'])) {
  21. // Login
  22. $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
  23. $stmt->execute([$username]);
  24. $user = $stmt->fetch();
  25. if ($user && password_verify($_POST['password'], $user['password'])) {
  26. $_SESSION['user_id'] = $user['id'];
  27. header('Location: index.php');
  28. } else {
  29. echo "Invalid credentials.";
  30. }
  31. }
  32. }
  33. ?>
  34. <!DOCTYPE html>
  35. <html lang="en">
  36. <head>
  37. <meta charset="UTF-8">
  38. <title>Register/Login</title>
  39. <link rel="stylesheet" href="styles.css">
  40. </head>
  41. <body>
  42. <div class="container">
  43. <h2>Register</h2>
  44. <form method="POST">
  45. <input type="text" name="username" placeholder="Username" required>
  46. <input type="password" name="password" placeholder="Password" required>
  47. <button type="submit" name="register">Register</button>
  48. </form>
  49. <h2>Login</h2>
  50. <form method="POST">
  51. <input type="text" name="username" placeholder="Username" required>
  52. <input type="password" name="password" placeholder="Password" required>
  53. <button type="submit" name="login">Login</button>
  54. </form>
  55. </div>
  56. </body>
  57. </html>