Request

Your Slim app’s routes and middleware are given a PSR-7 request object thatrepresents the current HTTP request received by your web server. The requestobject implements the PSR-7 ServerRequestInterface with which you caninspect and manipulate the HTTP request method, headers, and body.

How to get the Request object

The PSR-7 request object is injected into your Slim application routes as thefirst argument to the route callback like this:

  1. <?php
  2. use Psr\Http\Message\ResponseInterface as Response;
  3. use Psr\Http\Message\ServerRequestInterface as Request;
  4. use Slim\Factory\AppFactory;
  5. require __DIR__ . '/../vendor/autoload.php';
  6. $app = AppFactory::create();
  7. $app->get('/hello', function (Request $request, Response $response) {
  8. $response->getBody()->write('Hello World');
  9. return $response;
  10. });
  11. $app->run();
Figure 1: Inject PSR-7 request into application route callback.

The PSR-7 request object is injected into your Slim application _middleware_as the first argument of the middleware callable like this:

  1. <?php
  2. use Psr\Http\Message\ResponseInterface as Response;
  3. use Psr\Http\Message\ServerRequestInterface as Request;
  4. use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
  5. use Slim\Factory\AppFactory;
  6. require __DIR__ . '/../vendor/autoload.php';
  7. $app = AppFactory::create();
  8. $app->add(function (ServerRequestInterface $request, RequestHandler $handler) {
  9. return $handler->handle($request);
  10. });
  11. // ...define app routes...
  12. $app->run();
Figure 2: Inject PSR-7 request into application middleware.

The Request Method

Every HTTP request has a method that is typically one of:

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • PATCH
  • OPTIONSYou can inspect the HTTP request’s method with the Request object methodappropriately named getMethod().
  1. $method = $request->getMethod();

It is possible to fake or override the HTTP request method. This isuseful if, for example, you need to mimic a PUT request using a traditionalweb browser that only supports GET or POST requests.

Heads Up! To enable request method overriding the Method Overriding Middleware must be injected into your application.

There are two ways to override the HTTP request method. You can include aMETHOD parameter in a POST request’s body. The HTTP request must use theapplication/x-www-form-urlencoded content type.

  1. POST /path HTTP/1.1
  2. Host: example.com
  3. Content-type: application/x-www-form-urlencoded
  4. Content-length: 22
  5. data=value&_METHOD=PUT
Figure 3: Override HTTP method with _METHOD parameter.

You can also override the HTTP request method with a customX-Http-Method-Override HTTP request header. This works with any HTTP requestcontent type.

  1. POST /path HTTP/1.1
  2. Host: example.com
  3. Content-type: application/json
  4. Content-length: 16
  5. X-Http-Method-Override: PUT
  6. {"data":"value"}
Figure 4: Override HTTP method with X-Http-Method-Override header.

The Request URI

Every HTTP request has a URI that identifies the requested applicationresource. The HTTP request URI has several parts:

  • Scheme (e.g. http or https)
  • Host (e.g. example.com)
  • Port (e.g. 80 or 443)
  • Path (e.g. /users/1)
  • Query string (e.g. sort=created&dir=asc)You can fetch the PSR-7 Request object’s URI object with its getUri() method:
  1. $uri = $request->getUri();

The PSR-7 Request object’s URI is itself an object that provides the followingmethods to inspect the HTTP request’s URL parts:

  • getScheme()
  • getAuthority()
  • getUserInfo()
  • getHost()
  • getPort()
  • getPath()
  • getBasePath()
  • getQuery() (returns the full query string, e.g. a=1&b=2)
  • getFragment()
  • getBaseUrl()You can get the query parameters as an associative array on the Request object using getQueryParams().

Base Path If your Slim application's front-controller lives in a physical subdirectory beneath your document root directory, you can fetch the HTTP request's physical base path (relative to the document root) with the Uri object's getBasePath() method. This will be an empty string if the Slim application is installed in the document root's top-most directory.

The Request Headers

Every HTTP request has headers. These are metadata that describe the HTTPrequest but are not visible in the request’s body. Slim’s PSR-7Request object provides several methods to inspect its headers.

Get All Headers

You can fetch all HTTP request headers as an associative array with the PSR-7Request object’s getHeaders() method. The resultant associative array’s keysare the header names and its values are themselves a numeric array of stringvalues for their respective header name.

  1. $headers = $request->getHeaders();
  2. foreach ($headers as $name => $values) {
  3. echo $name . ": " . implode(", ", $values);
  4. }
Figure 5: Fetch and iterate all HTTP request headers as an associative array.

Get One Header

You can get a single header’s value(s) with the PSR-7 Request object’s getHeader($name) method. This returns an array of values for the given header name. Remember, a singleHTTP header may have more than one value!

  1. $headerValueArray = $request->getHeader('Accept');
Figure 6: Get values for a specific HTTP header.

You may also fetch a comma-separated string with all values for a given headerwith the PSR-7 Request object’s getHeaderLine($name) method. Unlike thegetHeader($name) method, this method returns a comma-separated string.

  1. $headerValueString = $request->getHeaderLine('Accept');
Figure 7: Get single header's values as comma-separated string.

Detect Header

You can test for the presence of a header with the PSR-7 Request object’shasHeader($name) method.

  1. if ($request->hasHeader('Accept')) {
  2. // Do something
  3. }
Figure 8: Detect presence of a specific HTTP request header.

The Request Body

Every HTTP request has a body. If you are building a Slim application thatconsumes JSON or XML data, you can use the PSR-7 Request object’sgetParsedBody() method to parse the HTTP request body into a native PHP format. Note that body parsing differs from one PSR-7 implementation to another.

You may need to implement middleware in order to parse the incoming input depending on the PSR-7 implementation you have installed. Here is an example for parsing incoming JSON input:

  1. <?php
  2. use Psr\Http\Message\ResponseInterface as Response;
  3. use Psr\Http\Message\ServerRequestInterface as Request;
  4. use Psr\Http\Server\MiddlewareInterface;
  5. use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
  6. class JsonBodyParserMiddleware implements MiddlewareInterface
  7. {
  8. public function process(Request $request, RequestHandler $handler): Response
  9. {
  10. $contentType = $request->getHeaderLine('Content-Type');
  11. if (strstr($contentType, 'application/json')) {
  12. $contents = json_decode(file_get_contents('php://input'), true);
  13. if (json_last_error() === JSON_ERROR_NONE) {
  14. $request = $request->withParsedBody($contents);
  15. }
  16. }
  17. return $handler->handle($request);
  18. }
  19. }
  1. $parsedBody = $request->getParsedBody();
Figure 9: Parse HTTP request body into native PHP format

Technically speaking, the PSR-7 Request object represents the HTTP requestbody as an instance of Psr\Http\Message\StreamInterface. You can getthe HTTP request body StreamInterface instance with the PSR-7 Request object’sgetBody() method. The getBody() method is preferable if the incoming HTTPrequest size is unknown or too large for available memory.

  1. $body = $request->getBody();
Figure 10: Get HTTP request body

The resultant Psr\Http\Message\StreamInterface instance provides the followingmethods to read and iterate its underlying PHP resource.

  • getSize()
  • tell()
  • eof()
  • isSeekable()
  • seek()
  • rewind()
  • isWritable()
  • write($string)
  • isReadable()
  • read($length)
  • getContents()
  • getMetadata($key = null)

Uploaded Files

The file uploads in $_FILES are available from the Request object’sgetUploadedFiles() method. This returns an array keyed by the name of theinput element.

  1. $files = $request->getUploadedFiles();
Figure 11: Get uploaded files

Each object in the $files array is a instance ofPsr\Http\Message\UploadedFileInterface and supports the following methods:

  • getStream()
  • moveTo($targetPath)
  • getSize()
  • getError()
  • getClientFilename()
  • getClientMediaType()See the cookbook on how to upload files using a POST form.

Request Helpers

Slim’s PSR-7 Request implementation provides these additional proprietary methodsto help you further inspect the HTTP request.

Detect XHR requests

You can detect XHR requests by checking if the header X-Requested-With is XMLHttpRequest using the Request’s getHeaderLine() method.

  1. POST /path HTTP/1.1
  2. Host: example.com
  3. Content-type: application/x-www-form-urlencoded
  4. Content-length: 7
  5. X-Requested-With: XMLHttpRequest
  6. foo=bar
Figure 13: Example XHR request.
  1. if ($request->getHeaderLine('X-Requested-With') === 'XMLHttpRequest') {
  2. // Do something
  3. }

Content Type

You can fetch the HTTP request content type with the Request object’s getHeaderLine() method.

  1. $contentType = $request->getHeaderLine('Content-Type');

Content Length

You can fetch the HTTP request content length with the Request object’s getHeaderLine() method.

  1. $length = $request->getHeaderLine('Content-Length');

Request Parameter

To fetch single request parameter value. You will need to use getServerParams()

For example, to get a single Server Parameter:

  1. $params = $request->getServerParams();
  2. $authorization = isset($params['HTTP_AUTHORIZATION']) : $params['HTTP_AUTHORIZATION'] : null;

Route Object

Sometimes in middleware you require the parameter of your route.

In this example we are checking first that the user is logged in and second that the user has permissions to view the particular video they are attempting to view.

  1. <?php
  2. $app
  3. ->get('/course/{id}', Video::class.":watch")
  4. ->add(PermissionMiddleware::class);
  1. <?php
  2. use Psr\Http\Message\ServerRequestInterface as Request;
  3. use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
  4. use Slim\Routing\RouteContext;
  5. class PermissionMiddleware {
  6. public function __invoke(Request $request, RequestHandler $handler) {
  7. $routeContext = RouteContext::fromRequest($request);
  8. $route = $routeContext->getRoute();
  9. $courseId = $route->getArgument('id');
  10. // ...do permission logic...
  11. return $handler->handle($request);
  12. }
  13. }

Attributes

With PSR-7 it is possible to inject objects/values into the request object for further processing. In your applications middleware often need to pass along information to your route closure and the way to do is it is to add it to the request object via an attribute.

Example, Setting a value on your request object.

  1. $app->add(function ($request, $handler) {
  2. // add the session storage to your request as [READ-ONLY]
  3. $request = $request->withAttribute('session', $_SESSION);
  4. return $handler->handle($request);
  5. });

Example, how to retrieve the value.

  1. $app->get('/test', function ($request, $response, $args) {
  2. $session = $request->getAttribute('session'); // get the session from the request
  3. return $response->write('Yay, ' . $session['name']);
  4. });

The request object also has bulk functions as well. $request->getAttributes() and $request->withAttributes()