39 lines
1.5 KiB
PHP
39 lines
1.5 KiB
PHP
<?php
|
|
session_start();
|
|
header("Content-Type: application/json; charset=UTF-8");
|
|
header("Access-Control-Allow-Methods: POST");
|
|
require_once '../koneksi.php';
|
|
|
|
$data = json_decode(file_get_contents("php://input"));
|
|
|
|
if (!empty($data->username) && !empty($data->password)) {
|
|
if (strlen($data->password) < 8) {
|
|
http_response_code(400);
|
|
die(json_encode(["error" => "Password minimal harus 8 karakter!"]));
|
|
}
|
|
|
|
try {
|
|
// Cek apakah username sudah ada
|
|
$stmt = $conn->prepare("SELECT id FROM users WHERE username = :username");
|
|
$stmt->bindValue(':username', $data->username);
|
|
$stmt->execute();
|
|
if($stmt->rowCount() > 0) {
|
|
http_response_code(400); die(json_encode(["error" => "Username sudah terdaftar, gunakan yang lain!"]));
|
|
}
|
|
|
|
// Enkripsi password menggunakan BCRYPT
|
|
$query = "INSERT INTO users (username, password, role) VALUES (:username, :password, 'user')";
|
|
$stmt = $conn->prepare($query);
|
|
$stmt->bindValue(':username', htmlspecialchars(strip_tags($data->username)));
|
|
$stmt->bindValue(':password', password_hash($data->password, PASSWORD_BCRYPT));
|
|
|
|
if($stmt->execute()) {
|
|
echo json_encode(["pesan" => "Registrasi berhasil, silakan login!"]);
|
|
}
|
|
} catch(PDOException $e) {
|
|
http_response_code(500); echo json_encode(["error" => "Database Error: " . $e->getMessage()]);
|
|
}
|
|
} else {
|
|
http_response_code(400); echo json_encode(["error" => "Username dan Password wajib diisi."]);
|
|
}
|
|
?>
|