78 lines
2.1 KiB
PHP
78 lines
2.1 KiB
PHP
<?php
|
|
date_default_timezone_set('Asia/Jakarta');
|
|
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
|
|
header('Access-Control-Allow-Headers: Content-Type, Authorization');
|
|
header('Access-Control-Max-Age: 86400');
|
|
header('Content-Type: application/json');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
|
http_response_code(200);
|
|
exit();
|
|
}
|
|
|
|
include 'Connection.php';
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$username = trim($input['username'] ?? $_POST['username'] ?? '');
|
|
$password = $input['password'] ?? $_POST['password'] ?? '';
|
|
|
|
if (empty($username) || empty($password)) {
|
|
echo json_encode(["status" => "error", "message" => "Username and password are required"]);
|
|
exit;
|
|
}
|
|
|
|
if (strlen($password) < 6) {
|
|
echo json_encode(["status" => "error", "message" => "Password must be at least 6 characters"]);
|
|
exit;
|
|
}
|
|
|
|
if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
|
|
echo json_encode(["status" => "error", "message" => "Invalid username format"]);
|
|
exit;
|
|
}
|
|
|
|
$check = $conn->prepare("SELECT id FROM users WHERE username = ?");
|
|
$check->bind_param("s", $username);
|
|
$check->execute();
|
|
$check->store_result();
|
|
|
|
if ($check->num_rows > 0) {
|
|
echo json_encode(["status" => "error", "message" => "Username already taken"]);
|
|
$check->close();
|
|
$conn->close();
|
|
exit;
|
|
}
|
|
$check->close();
|
|
|
|
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
|
|
$created_at = date("Y-m-d H:i:s");
|
|
|
|
$stmt = $conn->prepare(
|
|
"INSERT INTO users (username, password, created_at) VALUES (?, ?, ?)"
|
|
);
|
|
$stmt->bind_param("sss", $username, $hashedPassword, $created_at);
|
|
|
|
if ($stmt->execute()) {
|
|
$new_user_id = $stmt->insert_id;
|
|
|
|
session_start();
|
|
$_SESSION['user_id'] = $new_user_id;
|
|
$_SESSION['username'] = $username;
|
|
|
|
echo json_encode([
|
|
"status" => "success",
|
|
"message" => "Registration successful",
|
|
"registered_at" => $created_at
|
|
]);
|
|
} else {
|
|
echo json_encode([
|
|
"status" => "error",
|
|
"message" => "Registration failed"
|
|
]);
|
|
}
|
|
|
|
$stmt->close();
|
|
$conn->close();
|
|
?>
|