Drupal - How to get $_POST and $_GET parameters
From the change record:
$name = $_POST['name']; // form param
becomes
$name = \Drupal::request()->request->get('name'); // form param
Incidentally, for GET
vars, you would use:
$query = \Drupal::request()->query->get('name');
In a controller get the request with a type-hinted argument Request $request
:
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
class ExampleController extends ControllerBase {
/**
* Controller to return a POST or a GET parameter.
*/
public function action(Request $request) {
// get your POST parameter
$foo = $request->request->get('foo');
// or get your GET parameter
$foo = $request->query->get('foo');
// POST requests are not cached, but for GET you need a cache context
return [
'#markup' => $foo,
'#cache' => ['contexts' => ['url.query_args:foo']],
];
}
}
More info https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes
Inject the RequestStack
into your controller.
The current request contains the query
attribute that in turn contains the GET parameters. request
contains the POST parameters.
<?php
namespace Drupal\example_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* An example controller.
*/
class ExampleController extends ControllerBase {
/**
* @var Symfony\Component\HttpFoundation\RequestStack
*/
private $requestStack;
/**
* Constructor.
*
* @param Symfony\Component\HttpFoundation\RequestStack $request_stack
*/
public function __construct(RequestStack $request_stack) {
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('request_stack')
);
}
/**
* {@inheritdoc}
*/
public function action() {
// Get your GET parameter here.
$this->requestStack->getCurrentRequest()->query->get('foo');
}
}