1. Go to this page and download the library: Download bairwell/middleware-cors library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
bairwell / middleware-cors example snippets
$slim = new \Slim\App(); // use Slim3 as it supports PSR7 middleware
// add CORs
$slim->add(new MiddlewareCors());
// add routes
$slim->run(); // get Slim running
$slim = new \Slim\App(); // use Slim3 as it supports PSR7 middleware
$config = [
'origin' => '*.example.com' // allow all hosts ending example.com
];
// add CORs
$slim->add(new MiddlewareCors($config));
// add routes
$slim->run(); // get Slim running
$slim = new \Slim\App(); // use Slim3 as it supports PSR7 middleware
$config = [
'origin' => ['*.example.com', '*.example.com.test', 'example.com', 'dev.*'],
'allowCredentials' => true
];
$slim->add(new MiddlewareCors($config)); // add CORs
// add routes
$slim->run(); // get Slim running
// read the allowed methods for a route
$corsAllowedMethods = function (ServerRequestInterface $request) use ($container) : array {
// if this closure is called, make sure it has the route available in the container.
/* @var RouterInterface $router */
$router = $container->get('router');
$routeInfo = $router->dispatch($request);
$methods = [];
// was the method called allowed?
if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
$methods = $routeInfo[1];
} else {
// if it was, see if we can get the routes and then the methods from it.
// @var \Slim\Route $route
$route = $request->getAttribute('route');
// has the request get a route defined? is so use that
if (null !== $route) {
$methods = $route->getMethods();
}
}
// if we have methods, let's list them removing the OPTIONs one.
if (0 === count($methods)) {
// find the OPTIONs method
$key = array_search('OPTIONS', $methods,true);
// and remove it if set.
if (false !== $key) {
unset($methods[$key]);
$methods = array_values($methods);
}
}
return $methods;
};
$cors = new MiddlewareCors([
'origin' => ['*.example.com','example.com','*.example.com.test','192.168.*','10.*'],
'exposeHeaders' => '',
'maxAge' => 120,
'allowCredentials' => true,
'allowMethods' => $corsAllowedMethods,
'allowHeaders' => ['Accept', 'Accept-Language', 'Authorization', 'Content-Type','DNT','Keep-Alive','User-Agent','X-Requested-With','If-Modified-Since','Cache-Control','Origin'],
]);
$slim->add($cors);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.