76 lines
2.9 KiB
PHP
76 lines
2.9 KiB
PHP
<?php
|
|
require_once 'partials/header.php';
|
|
require_once 'db/config.php';
|
|
|
|
$errors = [];
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$username = $_POST['username'] ?? '';
|
|
$email = $_POST['email'] ?? '';
|
|
$password = $_POST['password'] ?? '';
|
|
|
|
if (empty($username)) {
|
|
$errors[] = 'Username is required';
|
|
}
|
|
if (empty($email)) {
|
|
$errors[] = 'Email is required';
|
|
}
|
|
if (empty($password)) {
|
|
$errors[] = 'Password is required';
|
|
}
|
|
|
|
if (empty($errors)) {
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare('SELECT id FROM users WHERE username = :username OR email = :email');
|
|
$stmt->execute([':username' => $username, ':email' => $email]);
|
|
if ($stmt->fetch()) {
|
|
$errors[] = 'Username or email already exists';
|
|
} else {
|
|
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
|
|
$stmt = $pdo->prepare('INSERT INTO users (username, email, password) VALUES (:username, :email, :password)');
|
|
$stmt->execute([':username' => $username, ':email' => $email, ':password' => $hashed_password]);
|
|
$_SESSION['user_id'] = $pdo->lastInsertId();
|
|
header('Location: index.php');
|
|
exit;
|
|
}
|
|
} catch (PDOException $e) {
|
|
$errors[] = 'Database error: ' . $e->getMessage();
|
|
}
|
|
}
|
|
}
|
|
?>
|
|
|
|
<div class="row justify-content-center">
|
|
<div class="col-md-6">
|
|
<div class="card">
|
|
<div class="card-header">Register</div>
|
|
<div class="card-body">
|
|
<?php if (!empty($errors)): ?>
|
|
<div class="alert alert-danger">
|
|
<?php foreach ($errors as $error): ?>
|
|
<p><?php echo $error; ?></p>
|
|
<?php endforeach; ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
<form method="POST">
|
|
<div class="mb-3">
|
|
<label for="username" class="form-label">Username</label>
|
|
<input type="text" class="form-control" id="username" name="username" required>
|
|
</div>
|
|
<div class="mb-3">
|
|
<label for="email" class="form-label">Email address</label>
|
|
<input type="email" class="form-control" id="email" name="email" required>
|
|
</div>
|
|
<div class="mb-3">
|
|
<label for="password" class="form-label">Password</label>
|
|
<input type="password" class="form-control" id="password" name="password" required>
|
|
</div>
|
|
<button type="submit" class="btn btn-primary">Register</button>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<?php require_once 'partials/footer.php'; ?>
|