phpfastroute

nikic/FastRoute post request parameter access


I am trying to implement simple POST request using FastRoute. I sucefully implemented GET type request by following the given example. While implementing the POST request I am not able access the parameters that were send with request.

$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
  $r->addRoute('POST', '/login', 'Test/put');
  $r->addRoute('GET', '/users/{id:\d+}', 'Test/put');
});

$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];

if (false !== $pos = strpos($uri, '?')) {
 $uri = substr($uri, 0, $pos);
}

$uri = rawurldecode($uri);

$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
 case FastRoute\Dispatcher::FOUND:
  $handler = $routeInfo[1];
  $vars = $routeInfo[2];
  list($class, $method) = explode("/", $handler, 2);
  call_user_func_array(array(new $class, $method), $vars);
  break;
}

class Test {
 public function put() {
  return "Check";
 }
}

I tried to check $_POST, However, that is empty.


Solution

  • After searching a good deal regarding nikic/FastRoute post request, stumble upon this stackoverflow post. After that have made the following changes to the code.

    $_POST = json_decode(file_get_contents('php://input' ),true);
    
    $dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
      $r->addRoute('POST', '/login', 'Test/put');
      $r->addRoute('GET', '/users/{id:\d+}', 'Test/put');
    });
    
    $httpMethod = $_SERVER['REQUEST_METHOD'];
    $uri = $_SERVER['REQUEST_URI'];
    
    if (false !== $pos = strpos($uri, '?')) {
     $uri = substr($uri, 0, $pos);
    }
    
    $uri = rawurldecode($uri);
    $httpMethod = $_SERVER['REQUEST_METHOD'];
    $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
    switch ($routeInfo[0]) {
     case FastRoute\Dispatcher::FOUND:
       $handler = $routeInfo[1];
       $vars = ($httpMethod == 'POST')? $_POST : $routeInfo[2];;
       list($class, $method) = explode("/", $handler, 2);
       call_user_func_array(array(new $class, $method), $vars);
       break;
    }
    
    class Test {
      public function put() {
        return "Check";
      }
    }