41 lines
1.1 KiB
PHP
41 lines
1.1 KiB
PHP
<?php
|
|
session_start();
|
|
header('Content-Type: application/json');
|
|
require_once __DIR__ . '/../database/db_connect.php';
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$username = trim($input['username'] ?? '');
|
|
$password = $input['password'] ?? '';
|
|
|
|
if (!$username || !$password) {
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Username and password required']);
|
|
exit;
|
|
}
|
|
|
|
// Check if user exists
|
|
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
|
|
$stmt->execute([$username]);
|
|
if ($stmt->fetch()) {
|
|
http_response_code(409);
|
|
echo json_encode(['error' => 'Username already taken']);
|
|
exit;
|
|
}
|
|
|
|
// Hash password
|
|
$hash = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
// Insert user
|
|
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
|
|
if ($stmt->execute([$username, $hash])) {
|
|
$userId = $pdo->lastInsertId();
|
|
$_SESSION['user_id'] = $userId;
|
|
$_SESSION['username'] = $username;
|
|
|
|
echo json_encode(['ok' => true, 'user' => ['id' => $userId, 'username' => $username]]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => 'Registration failed']);
|
|
}
|
|
?>
|