61 lines
1.9 KiB
PHP
61 lines
1.9 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../db/config.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$data || !isset($data['email']) || !isset($data['password']) || !isset($data['username'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['status' => 'error', 'message' => 'Invalid input.']);
|
|
exit;
|
|
}
|
|
|
|
$username = trim($data['username']);
|
|
$email = trim($data['email']);
|
|
$password = $data['password'];
|
|
|
|
if (empty($username) || empty($email) || empty($password)) {
|
|
http_response_code(400);
|
|
echo json_encode(['status' => 'error', 'message' => 'Please fill all fields.']);
|
|
exit;
|
|
}
|
|
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
http_response_code(400);
|
|
echo json_encode(['status' => 'error', 'message' => 'Invalid email format.']);
|
|
exit;
|
|
}
|
|
|
|
if (strlen($password) < 6) {
|
|
http_response_code(400);
|
|
echo json_encode(['status' => 'error', 'message' => 'Password must be at least 6 characters long.']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
// Check if username or email already exists
|
|
$stmt = $pdo->prepare('SELECT id FROM users WHERE username = ? OR email = ?');
|
|
$stmt->execute([$username, $email]);
|
|
if ($stmt->fetch()) {
|
|
http_response_code(409);
|
|
echo json_encode(['status' => 'error', 'message' => 'Username or email already taken.']);
|
|
exit;
|
|
}
|
|
|
|
// Hash the password
|
|
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
// Insert new user
|
|
$stmt = $pdo->prepare('INSERT INTO users (username, email, password) VALUES (?, ?, ?)');
|
|
$stmt->execute([$username, $email, $hashedPassword]);
|
|
|
|
echo json_encode(['status' => 'success', 'message' => 'Registration successful. You can now log in.']);
|
|
|
|
} catch (PDOException $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
|
|
}
|