68 lines
2.1 KiB
PHP
68 lines
2.1 KiB
PHP
|
|
<?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; ?>
|