CORS Middleware for PHP Slim Framework

Related tags

Frameworks CorsSlim
Overview

CorsSlim

Cross-origin resource sharing (CORS) Middleware for PHP Slim Framework.

Latest Stable Version Build Status License

Usage

Composer Autoloader

Install with Composer

  1. Update your composer.json to require palanik/corsslim package.
  2. Run composer install to add CorsSlim your vendor folder.
{
  "require": {
    "palanik/corsslim": "*"
  }
}

Autoloading

<?php
require ('./vendor/autoload.php');

$app = new \Slim\Slim();

$app->add(new \CorsSlim\CorsSlim());
?>

Custom Load

<?php
\Slim\Slim::registerAutoLoader();

$app = new \Slim\Slim();

require ('path_to_your_middlewares/CorsSlim.php');
$app->add(new \CorsSlim\CorsSlim());
?>

Options

You can create the middleware with custom options. Pass options as associative array.

Example

$corsOptions = array(
    "origin" => "*",
    "exposeHeaders" => array("X-My-Custom-Header", "X-Another-Custom-Header"),
    "maxAge" => 1728000,
    "allowCredentials" => True,
    "allowMethods" => array("POST, GET"),
    "allowHeaders" => array("X-PINGOTHER")
    );
$cors = new \CorsSlim\CorsSlim($corsOptions);

Whitelisted Origins

Set an array of allowed origins to origin option. If a matching request origin found it is used.

Example

$corsOptions = array(
    "origin" => array('http://one.allowed-origin.com', 'http://two.allowed-origin.com'),
    "exposeHeaders" => array("X-My-Custom-Header", "X-Another-Custom-Header"),
    "maxAge" => 1728000,
    "allowCredentials" => True,
    "allowMethods" => array("POST, GET"),
    "allowHeaders" => array("X-PINGOTHER")
    );
$cors = new \CorsSlim\CorsSlim($corsOptions);

Route Middleware

New

You can now enable cors selectively for individual routes.

Use the static method routeMiddleware to create and add cors middleware to specific routes.

<?php
require ('./vendor/autoload.php');
$app = new \Slim\Slim();

$app->get('/item/:id', 
          \CorsSlim\CorsSlim::routeMiddleware(), 
          function ($name) use ($app) {
            ...
          }
        );
?>

Also with custom options.

<?php
require ('./vendor/autoload.php');
$app = new \Slim\Slim();

$corsOptions = array("origin" => "*");
$app->get('/item/:id', 
          \CorsSlim\CorsSlim::routeMiddleware($corsOptions), 
          function ($name) use ($app) {
            ...
          }
        );

?>

For Preflighted requests, provide OPTIONS implementation for the corresponding routes.

<?php
require ('./vendor/autoload.php');
$app = new \Slim\Slim();

$app->options('/item', 
          \CorsSlim\CorsSlim::routeMiddleware(), 
          function ($name) use ($app) {}
        );
$app->post('/item', 
          \CorsSlim\CorsSlim::routeMiddleware(), 
          function ($name) use ($app) {
            ...
          }
        );

?>

License

MIT

Comments
  • 301 Permanent Moved on heroku

    301 Permanent Moved on heroku

    Can't figure why.. I use CorsSlim with default Settings and when I try to access it from another heroku repo I keep getting an 301 Permanent Moved Any Ideas ?

    EDIT: And If I try the same request with postman it works like charm...

    request:

        Host: lavacal-api.heroku.com
        User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0
        Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        Accept-Language: de,en-US;q=0.7,en;q=0.3
        Accept-Encoding: gzip, deflate
        Origin: http://lavacal.herokuapp.com
        Access-Control-Request-Method: GET
        Access-Control-Request-Headers: apikey
        Connection: keep-alive
    

    response:

        Connection: keep-alive
        Content-Length: 0
        Date: Mon, 20 Apr 2015 16:30:41 GMT
        Location: http://lavacal-api.herokuapp.com/api/v1/events
        Server: Cowboy
    
    opened by marvinosswald 5
  • Which headers do I need to expose for session cookies?

    Which headers do I need to expose for session cookies?

    I'm having trouble persisting sessions across requests made via cross-origin requests. I'm starting to suspect this has something to do with the way the response headers are modified by CorsSlim.

    Do I need to set exposeHeaders? If so, which headers do I need to expose for sessions to work properly? Just the Set-Cookie header?

    opened by alexweissman 2
  • empty POST parameters

    empty POST parameters

    Hello palanik! thanks to share this library!

    The api works great in GET request, but in POST request when i retrieve parameters with:

    $req = $app->request()->post();

    $req is empty, but in developer console (Chrome) Request-Payload contains data.

    Do you have tips?

    Thanks in advance

    opened by ilvalerione 2
  • Add support for multiple origins by using an array for the origin setting.

    Add support for multiple origins by using an array for the origin setting.

    Add support for multiple origins if an array is passed in for the 'origin' setting. This works by returning the first value to match the actual origin of the request, or defaulting to the first value in the array.

    opened by CodeCommander 2
  • How to dynamically load origin?

    How to dynamically load origin?

    Hi, I have a column in a database table that stores the domain that an app will be accessing our API from.

    I would like to be able to dynamically load the domain from the database and include it as the origin option of the middleware.

    What is the best way to do this? I tried doing a query but it didn't work. How would I dynamically load a whitelist of domains?

    opened by mromarreyes 1
  • ExposeHeaders does not work

    ExposeHeaders does not work

    You must fix the setExposeHeaders method. You're using -> instead array notation

    protected function setExposeHeaders($req, $rsp) {
        if (isset($this->settings['exposeHeaders'])) {
            $exposeHeaders = $this->settings['exposeHeaders'];
            if (is_array($exposeHeaders)) {
                $exposeHeaders = implode(", ", $exposeHeaders);
            }
    
            $rsp->headers->set('Access-Control-Expose-Headers', $exposeHeaders);
        }
    }
    
    opened by adrianofoschi 1
  •  Cannot access protected property Slim\Slim::$request

    Cannot access protected property Slim\Slim::$request

    Fatal error: Cannot access protected property Slim\Slim::$request in /var/www/site/web/vendor/palanik/corsslim/CorsSlim.php on line 100

    Do you have an idea what the problem could be here?

    opened by bujardeari 1
  • CORS headers not set on exception (SLIM bypasses middleware)

    CORS headers not set on exception (SLIM bypasses middleware)

    The problem is that SLIM bypasses the middleware that sets the CORS headers in some cases. A quick patch would be to change protected function setCorsHeaders($req, $rsp)

    Into public function setCorsHeaders($req, $rsp) {

    So this function can be called 'manually' from the (custom) 404, 406 and Errorhandlers.

    But maybe it is not a big problem at all. Or maybe there is a better solution.

    We use: "palanik/corsslim": "dev-slim3"

    opened by patricksavalle 0
  • Route Middleware not work

    Route Middleware not work

    Hi!

    This is my code, but not work:

    require ('.././libs/CorsSlim/vendor/autoload.php');
    $app = new \Slim\Slim();
    
    $app->post('/item', 
              \CorsSlim\CorsSlim::routeMiddleware(), 
              function () use ($app) {
                $r = json_decode($app->request->getBody());
                $response["status"] = "success";
                $response["message"] = $r->data->nickname;
                echoResponse(200, $response);
              }
            );
    

    The error:

    XMLHttpRequest cannot load [...]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

    If I use this code, it works. But I need apply only in one route:

    require ('.././libs/CorsSlim/vendor/autoload.php');
    $app = new \Slim\Slim();
    
    $corsOptions = array(
        "origin" => "*",
        "exposeHeaders" => array("X-My-Custom-Header", "X-Another-Custom-Header"),
        "maxAge" => 1728000,
        "allowCredentials" => True,
        "allowMethods" => array("POST, GET"),
        "allowHeaders" => array("Origin, X-Requested-With, Content-Type, Accept")
        );
    
    $cors = new \CorsSlim\CorsSlim($corsOptions);
    $app->post('/item',
              function () use ($app) {
                $r = json_decode($app->request->getBody());
                $response["status"] = "success";
                $response["message"] = $r->data->nickname;
                echoResponse(200, $response);
              }
            );
    
    $app->add($cors);
    
    opened by shotoreaper 3
Owner
Palani Kumanan
Engineer in @WSJ Newsroom https://github.com/save-net-neutrality
Palani Kumanan
This repository contains a library of optional middleware for your Slim Framework application

Slim Framework Middleware This repository contains a library of optional middleware for your Slim Framework application. How to Install Update your co

Slim Framework 47 Nov 7, 2022
Juliangut Slim Framework Doctrine handler middleware

Juliangut Slim Framework Doctrine handler middleware Doctrine handler middleware for Slim Framework. Slim3 version Doctrine integration service for Sl

Julián Gutiérrez 6 Mar 23, 2021
This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library

This Slim Framework middleware will compile LESS CSS files on-the-fly using the Assetic library. It supports minification and caching, also via Asseti

Gerard Sychay 22 Mar 31, 2020
Access control middleware for Slim framework

Slim Access Access control middleware for Slim framework. Supported formats IPv4 and IPv6 addresses CIDR notation all keyword Installation composer re

Alexandre Bouvier 7 Oct 22, 2019
Redis cache middleware for Slim framework

RedisCache Redis cache middleware for Slim framework. Installation composer require abouvier/slim-redis-cache Usage Cache every successful HTTP respo

Alexandre Bouvier 16 Sep 20, 2021
Slim Framework HTTP cache middleware and service provider

Slim Framework HTTP Cache This repository contains a Slim Framework HTTP cache middleware and service provider. Install Via Composer $ composer requir

Slim Framework 107 Dec 15, 2022
Slim Framework CSRF protection middleware

Slim Framework CSRF Protection This repository contains a Slim Framework CSRF protection PSR-15 middleware. CSRF protection applies to all unsafe HTTP

Slim Framework 302 Dec 11, 2022
This package has framework agnostic Cross-Origin Resource Sharing (CORS) implementation.

Description This package has framework agnostic Cross-Origin Resource Sharing (CORS) implementation. It is complaint with PSR-7 HTTP message interface

null 60 Nov 9, 2022
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Slim Framework Slim is a PHP micro-framework that helps you quickly write simple yet powerful web applications and APIs. Installation It's recommended

Slim Framework 11.5k Jan 4, 2023
A Slim PHP MVC framework built just for fun!

Aura Framework A Slim PHP MVC framework built just for fun! en: Note: This repository only contains the core code of the Aura framework. If you want t

Murilo Magalhães Barreto 2 Dec 16, 2021
The Slim PHP micro framework paired with Laravel's Illuminate Database toolkit.

Slim & Eloquent The Slim PHP micro framework paired with Laravel's Illuminate Database toolkit. Getting started # Download composer curl -s https://ge

Kyle Ladd 111 Jul 23, 2022
PHP boilerplate for quick start projects using Slim Framework and Eloquent.

Lassi PHP boilerplate for quick projects using Slim Framework and Eloquent database. Lassi is a small PHP boilerplate to use Slim Framework with Eloqu

Jabran Rafique⚡️ 59 Jul 14, 2022
Slim Framework - Prerequisite Checker

Slim Framework - Server Configuration Checker Upload the file check.php to your webserver Browse to the file: https://example.com/check.php Check the

Daniel Opitz 6 Aug 30, 2022
REST APIs using Slim framework. Implemented all CRUD operations on the MySql database

PHP REST API using slim framework and CRUD operations ?? Hi there, this is a simple REST API built using the Slim framework. And this is for the folks

Hanoak 2 Jun 1, 2022
Slim Framework skeleton application with MVC Schema

Slim Framework skeleton application with MVC Schema

JingwenTian 9 Apr 29, 2021
A curated list of awesome tutorials and other resources for the Slim micro framework

Awesome Slim A curated list of awesome tutorials and other resources for the Slim micro framework Table of Contents Essentials Tutorials Packages and

Sawyer Charles 466 Dec 8, 2022
Slim Framework 3 Skeleton Application + PagSeguro Lib

Slim Framework 3 Skeleton Application + PagSeguro Lib Aplicação simples para geração do Token para pagamentos no PagSeguro (método transparente) e env

Raí Siqueira 1 Feb 26, 2018
My personal blog developed on the Slim Framework

nesbot.com I am making the source code of my personal site available publicly in case it helps anybody. It's developed using the Slim Framework. I am

Brian Nesbitt 56 Sep 14, 2022
Plates Template Integration for Slim micro framework 3

Plates Template Integration for Slim micro framework 3 Render your Slim 3 application views using Plates template engine. Install Via Composer $ compo

Projek XYZ 26 Feb 5, 2022