Last active
February 23, 2019 06:14
-
-
Save ryanscherler/b325c7fc0d0c59b5a7583c9d3971f635 to your computer and use it in GitHub Desktop.
Slim PHP Host Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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