kelompok06-2048/Register.php
2025-12-03 11:16:57 +07:00

98 lines
2.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
// ✅ Set timezone Indonesia (WIB)
date_default_timezone_set('Asia/Jakarta');
// ✅ CORS Headers
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');
// ✅ Handle preflight OPTIONS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
include 'Connection.php';
// ✅ Handle input
$input = json_decode(file_get_contents('php://input'), true);
$username = trim($input['username'] ?? $_POST['username'] ?? '');
$password = $input['password'] ?? $_POST['password'] ?? '';
// ✅ Validasi input kosong
if (empty($username) || empty($password)) {
echo json_encode([
"status" => "error",
"message" => "Username and password are required"
]);
exit;
}
// ✅ Validasi panjang password
if (strlen($password) < 6) {
echo json_encode([
"status" => "error",
"message" => "Password must be at least 6 characters"
]);
exit;
}
// ✅ Validasi format username
if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
echo json_encode([
"status" => "error",
"message" => "Username may only contain letters, numbers, and underscores (320 characters)"
]);
exit;
}
// ✅ Cek apakah username sudah ada
$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 is already taken"
]);
$check->close();
$conn->close();
exit;
}
$check->close();
// ✅ Hash password dan insert ke database
$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()) {
// 🔥 PERBAIKAN UTAMA DI SINI (AUTO-LOGIN) 🔥
$new_user_id = $stmt->insert_id; // Ambil ID user baru
session_start();
$_SESSION['user_id'] = $new_user_id; // Set Session ID
$_SESSION['username'] = $username; // Set Session Username
echo json_encode([
"status" => "success",
"message" => "Registration successful",
"registered_at" => $created_at
]);
} else {
echo json_encode([
"status" => "error",
"message" => "Failed to register: " . $conn->error
]);
}
$stmt->close();
$conn->close();
?>