54 lines
1.5 KiB
PHP
54 lines
1.5 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
header('Location: index.php');
|
|
exit();
|
|
}
|
|
|
|
$username = trim($_POST['username'] ?? '');
|
|
$password = $_POST['password'] ?? '');
|
|
$confirm_password = $_POST['confirm_password'] ?? '');
|
|
|
|
// Basic validation
|
|
if (empty($username) || empty($password)) {
|
|
header('Location: index.php?reg_error=Username and password are required.#register');
|
|
exit();
|
|
}
|
|
|
|
if ($password !== $confirm_password) {
|
|
header('Location: index.php?reg_error=Passwords do not match.#register');
|
|
exit();
|
|
}
|
|
|
|
if (strlen($password) < 6) {
|
|
header('Location: index.php?reg_error=Password must be at least 6 characters long.#register');
|
|
exit();
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
// Check if username already exists
|
|
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
|
|
$stmt->execute([$username]);
|
|
if ($stmt->rowCount() > 0) {
|
|
header('Location: index.php?reg_error=Username already taken.#register');
|
|
exit();
|
|
}
|
|
|
|
// Hash password and insert user
|
|
$password_hash = password_hash($password, PASSWORD_DEFAULT);
|
|
$stmt = $pdo->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
|
|
$stmt->execute([$username, $password_hash]);
|
|
|
|
header('Location: index.php?reg_success=1#login');
|
|
exit();
|
|
|
|
} catch (PDOException $e) {
|
|
// In a real app, log the error
|
|
header('Location: index.php?reg_error=A database error occurred.#register');
|
|
exit();
|
|
}
|
|
?>
|