test_server.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. $headers = getallheaders();
  3. if (!isset($headers['Authorization']) || $headers['Authorization'] !== 'Bearer secret_token') {
  4. header('Content-Type: application/json');
  5. http_response_code(401);
  6. echo json_encode(['error' => 'Unauthorized']);
  7. exit(0);
  8. }
  9. header('Content-Type: application/json');
  10. $routes = [
  11. 'GET' => [
  12. '/api/data' => function () {
  13. echo json_encode(['message' => 'GET request received']);
  14. exit(0);
  15. },
  16. '/api/search' => function () {
  17. $name = $_GET['name'] ?? 'Guest';
  18. $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
  19. $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
  20. echo json_encode([
  21. 'message' => "GET request received",
  22. 'name' => $name,
  23. 'page' => $page,
  24. 'limit' => $limit
  25. ]);
  26. exit(0);
  27. }
  28. ],
  29. 'POST' => [
  30. '/api/post/data' => function () {
  31. if ('application/json' !== $_SERVER['CONTENT_TYPE']) {
  32. http_response_code(400);
  33. echo json_encode(['error' => 'Invalid content type']);
  34. exit(0);
  35. }
  36. $input = json_decode(file_get_contents('php://input'), true);
  37. if (json_last_error() !== JSON_ERROR_NONE) {
  38. http_response_code(400);
  39. echo json_encode(['error' => 'Invalid JSON']);
  40. exit(0);
  41. }
  42. echo json_encode($input);
  43. exit(0);
  44. },
  45. '/api/post/data/form' => function () {
  46. if ('application/x-www-form-urlencoded' !== $_SERVER['CONTENT_TYPE']) {
  47. http_response_code(400);
  48. echo json_encode(['error' => 'Invalid content type']);
  49. exit(0);
  50. }
  51. if (empty($_POST)) {
  52. http_response_code(400);
  53. echo json_encode(['error' => 'No data provided']);
  54. exit(0);
  55. }
  56. echo json_encode($_POST);
  57. exit(0);
  58. }
  59. ]
  60. ];
  61. if (array_key_exists($_SERVER['REQUEST_METHOD'], $routes)) {
  62. foreach ($routes[$_SERVER['REQUEST_METHOD']] as $route => $callback) {
  63. if ($route == strtok($_SERVER['REQUEST_URI'], '?')) {
  64. $callback();
  65. break;
  66. }
  67. }
  68. }
  69. http_response_code(404);
  70. echo json_encode(['error' => 'Not found', 'route' => $_SERVER['REQUEST_URI']]);
  71. exit(0);