skapade registrering, logga in och logga ut. ändrade lite i auth.php

This commit is contained in:
Dr3amFury
2025-07-17 20:23:16 +02:00
parent 9b8e7de960
commit 03159e12b5
6 changed files with 128 additions and 66 deletions

67
inc/php/register.php Normal file
View File

@@ -0,0 +1,67 @@
<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
// Validate inputs
if (empty($username) || empty($email) || empty($password)) {
$errors[] = "All fields are required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
if (strlen($password) < 6) {
$errors[] = "Password must be at least 6 characters.";
}
if (empty($errors)) {
$conn = getConnection();
// Check if email or username already exists
$stmt = $conn->prepare("SELECT id FROM users WHERE email = :email OR username = :username");
$stmt->execute(['email' => $email, 'username' => $username]);
if ($stmt->fetch()) {
$errors[] = "Email or username already in use.";
} else {
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$uniqueId = bin2hex(random_bytes(16)); // session ID
$insert = $conn->prepare("INSERT INTO users (username, email, password, uniqueid) VALUES (:username, :email, :password, :uniqueid)");
$insert->execute([
'username' => $username,
'email' => $email,
'password' => $hash,
'uniqueid' => $uniqueId,
]);
$_SESSION['user_id'] = $conn->lastInsertId();
$_SESSION['uniqueid'] = $uniqueId;
header("Location: /home.php");
exit();
}
}
}
?>
<!-- Basic form UI -->
<h2>Register</h2>
<form method="POST">
<input name="username" placeholder="Username" required><br>
<input name="email" type="email" placeholder="Email" required><br>
<input name="password" type="password" placeholder="Password" required><br>
<button type="submit">Register</button>
</form>
<?php if (!empty($errors)): ?>
<ul><?php foreach ($errors as $e) echo "<li>$e</li>"; ?></ul>
<?php endif; ?>