Skip to content

Instantly share code, notes, and snippets.

@tuupola
Created June 10, 2016 08:44
Show Gist options
  • Save tuupola/72474e9e2602ffb2c4fb087be3012789 to your computer and use it in GitHub Desktop.
Save tuupola/72474e9e2602ffb2c4fb087be3012789 to your computer and use it in GitHub Desktop.
CORS middleware with Zend Expressive
<?php
use Zend\Expressive\AppFactory;
require __DIR__ . "/../vendor/autoload.php;
$app = AppFactory::create();
$app->pipe(new \Tuupola\Middleware\Cors([
"origin" => ["*"],
"methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"],
"headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"],
"headers.expose" => ["Etag"],
"credentials" => true,
"cache" => 86400
]));
$app->get("/", function ($request, $response, $next) {
$response->getBody()->write("Hello, world!");
return $response;
});
$app->pipeRoutingMiddleware();
$app->pipeDispatchMiddleware();
$app->run();
$ php -S 0.0.0.0:80 index.php
$ curl localhost:8080 --include --header "Origin: http://www.example.com"
HTTP/1.1 200 OK
Host: localhost:8080
Connection: close
X-Powered-By: PHP/5.6.17
Access-Control-Allow-Origin: http://www.example.com
Access-Control-Allow-Credentials: true
Vary: Origin
Access-Control-Expose-Headers: Etag
Content-Length: 13
Content-type: text/html; charset=UTF-8
Hello, world!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment