true] + $arr, JSON_UNESCAPED_UNICODE); exit; } function out_err($msg, $code=400) { http_response_code($code); echo json_encode(['ok'=>false,'error'=>$msg], JSON_UNESCAPED_UNICODE); exit; } if ($action === 'register') { $u = trim($b['username'] ?? ''); $p = (string)($b['password'] ?? ''); if ($u === '' || $p === '') out_err('username/password required'); $st = db()->prepare("SELECT user_id FROM users WHERE username=?"); $st->execute([$u]); if ($st->fetch()) out_err('username exists', 409); $hash = password_hash($p, PASSWORD_DEFAULT); $ins = db()->prepare("INSERT INTO users(username, pass_hash) VALUES(?, ?)"); $ins->execute([$u, $hash]); out_ok(['user_id' => (int)db()->lastInsertId(), 'username' => $u]); } if ($action === 'login') { $u = trim($b['username'] ?? ''); $p = (string)($b['password'] ?? ''); if ($u === '' || $p === '') out_err('username/password required'); $st = db()->prepare("SELECT user_id, pass_hash FROM users WHERE username=?"); $st->execute([$u]); $row = $st->fetch(); if (!$row) out_err('invalid credentials', 401); if (!password_verify($p, $row['pass_hash'])) out_err('invalid credentials', 401); out_ok(['user_id' => (int)$row['user_id'], 'username' => $u]); } out_err('unknown action', 404);