35603-vm/register.php
Flatlogic Bot 23eab8271d v2
2025-11-09 18:56:18 +00:00

94 lines
3.3 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
$errors = [];
$username = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
// Validation
if (empty($username)) {
$errors[] = 'Username is required.';
}
if (empty($password)) {
$errors[] = 'Password is required.';
} elseif (strlen($password) < 6) {
$errors[] = 'Password must be at least 6 characters long.';
}
// Check if username already exists
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
$stmt->execute([$username]);
if ($stmt->fetch()) {
$errors[] = 'Username already taken. Please choose another one.';
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
// If no errors, create user
if (empty($errors)) {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
try {
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->execute([$username, $hashed_password]);
$_SESSION['message'] = 'Registration successful! You can now log in.';
$_SESSION['message_type'] = 'success';
header("Location: login.php");
exit;
} catch (PDOException $e) {
$errors[] = "Database error on user creation: " . $e->getMessage();
}
}
}
require_once __DIR__ . '/includes/header.php';
?>
<div class="row justify-content-center">
<div class="col-lg-5">
<div class="card task-card">
<div class="card-body p-4">
<h1 class="card-title h3 mb-4 text-center">Create Your Account</h1>
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p class="mb-0"><?php echo htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form action="register.php" method="POST">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>" 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 class="form-text">Password must be at least 6 characters long.</div>
</div>
<button type="submit" class="btn btn-primary w-100 py-2">Register</button>
</form>
<div class="text-center mt-4">
<p class="mb-0">Already have an account? <a href="login.php">Log in here</a>.</p>
</div>
</div>
</div>
</div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>