Skip to content

Instantly share code, notes, and snippets.

@ryanscherler
Last active February 23, 2019 06:14
Show Gist options
  • Save ryanscherler/b325c7fc0d0c59b5a7583c9d3971f635 to your computer and use it in GitHub Desktop.
Save ryanscherler/b325c7fc0d0c59b5a7583c9d3971f635 to your computer and use it in GitHub Desktop.
Slim PHP Host Middleware
<?php
namespace App\Middleware;
class HostMiddleware
{
/**
* Host middleware invokable class
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke($request, $response, $next)
{
$uri = $request->getUri();
$host = $uri->getHost();
$allowedHosts = explode(',', env('ALLOWED_HOSTS', 'localhost,127.0.0.1'));
// Ensure host is allowed
if (!in_array($host, $allowedHosts)) {
return $response->withJson([
'status' => 'error',
'message' => "Host {$host} is not allowed to access this resource.",
], 405);
}
$response = $next($request, $response);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment