PHP Implementing Basic Cors in Slim3

CORS, the bane of every web-dev existence. It's a pain to deal with so let me give you some boilerplate that will make it just work.

CORS

First off, Slim doesn't come with CORS support at all, but it does give you the tools to deal with everything!

There are 2 things that you need to worry about.

  1. The Pre-Flight Request [OPTIONS]
  2. Adding the CORS headers on all responses

Preflight Request

This is easily handled by a catch-all route.

// routes.php

//Enable CORS
$app->options('/{name:.+}', \Core\Http\CorsAction::class);

// CorsAction.php

namespace Core\Http;

class CorsAction
{
    public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response) {
        return $response->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

This class just add's the most basic CORS information that will cover most if not all of your use cases.

Middleware for the rest!

We can use a Middleware to ensure that we always add the CORS Headers to our responses.

//CorsMiddleware.php

namespace Core\Middleware;

class CorsMiddleware
{
    public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, $next) {

        /** @var $response \Slim\Http\Response */
        $response = $next($request, $response);

        return $response->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

    }
}

Simply add it to your slim app where you need CORS support.

It really should be this simple! Of course some of you might be a bit angered by the carpet bombing of this ;)

Written by Glenn Eggleton on Monday August 21, 2017
Permalink - Chapter: Slim