百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

psr7-middlewares

> 编程语言
开源

[已弃用] PSR-7 中间件集合

657 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

[已弃用] PSR-7 中间件集合

This package is deprecated in favor of the new PSR-15 standard. Check it out here

psr7-middlewares

Collection of PSR-7 middlewares.

Requirements

  • PHP >= 5.5
  • A PSR-7 HTTP Message implementation, for example zend-diactoros
  • A PSR-7 middleware dispatcher compatible with the following signature:
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

function (RequestInterface $request, ResponseInterface $response, callable $next) {
    // ...
}

So, you can use these midlewares with:

  • Relay
  • Expressive
  • Slim 3
  • Spiral
  • Middleman
  • etc...

Installation

This package is installable and autoloadable via Composer as oscarotero/psr7-middlewares.

$ composer require oscarotero/psr7-middlewares

Usage example:

…

Available middlewares

  • AccessLog
  • AttributeMapper
  • AuraRouter
  • AuraSession
  • BasePath
  • BasicAuthentication
  • BlockSpam
  • Cache
  • ClientIp
  • Cors
  • Csp
  • Csrf
  • DebugBar
  • Delay
  • DetectDevice
  • DigestAuthentication
  • EncodingNegotiator
  • ErrorHandler
  • Expires
  • FastRoute
  • FormTimestamp
  • Firewall
  • FormatNegotiator
  • Geolocate
  • GoogleAnalytics
  • Honeypot
  • Https
  • ImageTransformer
  • IncludeResponse
  • JsonSchema
  • LanguageNegotiation
  • LeagueRoute
  • MethodOverride
  • Minify
  • Payload
  • PhpSession
  • Piwik
  • ReadResponse
  • Recaptcha
  • Rename
  • ResponseTime
  • Robots
  • SaveResponse
  • Shutdown
  • TrailingSlash
  • Uuid
  • Whoops
  • Www

AccessLog

To generate access logs for each request using the Apache's access log format. This middleware requires a Psr log implementation, for example monolog:

use Psr7Middlewares\Middleware;
use Monolog\Logger;
use Monolog\Handler\ErrorLogHandler;

//Create the logger
$logger = new Logger('access');
$logger->pushHandler(new ErrorLogHandler());

$middlewares = [

    //Required to get the Ip
    Middleware::ClientIp(),

    Middleware::AccessLog($logger) //Instance of Psr\Log\LoggerInterface
        ->combined(true)           //(optional) To use the Combined Log Format instead the Common Log Format
];

AttributeMapper

Maps middleware specific attribute to regular request attribute under desired name:

…

AuraRouter

To use Aura.Router (3.x) as a middleware:

…

AuraSession

Creates a new Aura.Session instance with the request.

use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\AuraSession;

$middlewares = [

    Middleware::AuraSession(),
        ->factory($sessionFactory) //(optional) Intance of Aura\Session\SessionFactory
        ->name('my-session-name'), //(optional) custom session name

    function ($request, $response, $next) {
        //Get the session instance
        $session = AuraSession::getSession($request);

        return $response;
    }
];

BasePath

Removes the prefix from the uri path of the request. This is useful to combine with routers if the root of the website is in a subdirectory. For example, if the root of your website is /web/public, a request with the uri /web/public/post/34 will be converted to /post/34. You can provide the prefix to remove or let the middleware autodetect it. In the router you can retrieve the prefix removed or a callable to generate more urls with the base path.

use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\BasePath;

$middlewares = [

    Middleware::BasePath('/web/public') // (optional) The path to remove...
        ->autodetect(true),             // (optional) ...or/and autodetect the base path

    function ($request, $response, $next) {
        //Get the removed prefix
        $basePath = BasePath::getBasePath($request);

        //Get a callable to generate full paths
        $generator = BasePath::getGenerator($request);

        $generator('/other/path'); // /web/public/other/path

        return $response;
    }
];

BasicAuthentication

Implements the basic http authentication. You have to provide an array with all users and password:

use Psr7Middlewares\Middleware;

$middlewares = [

    Middleware::BasicAuthentication([
            'username1' => 'password1',
            'username2' => 'password2'
        ])
        ->realm('My realm'), //(optional) change the realm value

    function ($request, $response, $next) {
        $username = BasicAuthentication::getUsername($request);

        return $next($request, $response);
    }
];

BlockSpam

To block referral spam using the piwik/referrer-spam-blacklist list

use Psr7Middlewares\Middleware;

$middlewares = [

    Middleware::BlockSpam('spammers.txt'), //(optional) to set a custom spammers list instead the piwik's list
];

Cache

Requires micheh/psr7-cache. Saves the responses' headers in cache and returns a 304 response (Not modified) if the request is cached. It also adds Cache-Control and Last-Modified headers to the response. You need a cache library compatible with psr-6.

use Psr7Middlewares\Middleware;

$middlewares = [

    Middleware::Cache(new Psr6CachePool()) //the PSR-6 cache implementation
        ->cacheControl('max-age=3600'),    //(optional) to add this Cache-Control header to all responses
];

ClientIp

Detects the client ip(s).

…

Cors

To use the neomerx/cors-psr7 library:

…

Csp

To use the paragonie/csp-builder library to add the Content-Security-Policy header to the response.


$middlewares = [

    Middleware::csp($directives)                          //(optional) the array with the directives.
        ->addSource('img-src', 'https://ytimg.com')       //(optional) to add extra sources to whitelist
        ->addDirective('upgrade-insecure-requests', true) //(optional) to add new directives (if it doesn't already exist)
        ->supportOldBrowsers(false)                       //(optional) support old browsers (e.g. safari). True by default
];

Csrf

To add a protection layer agains CSRF (Cross Site Request Forgery). The middleware injects a hidden input with a token in all POST forms and them check whether the token is valid or not. Use ->autoInsert() to insert automatically the token or, if you prefer, use the generator callable:

…

DebugBar

Inserts the PHP debug bar 1.x in the html body. This middleware requires Middleware::formatNegotiator executed before, to insert the debug bar only in Html responses.

use Psr7Middlewares\Middleware;
use DebugBar\StandardDebugBar;

$debugBar = new StandardDebugBar();

$middlewares = [

    Middleware::FormatNegotiator(), //(recomended) to insert only in html responses

    Middleware::DebugBar($debugBar) //(optional) Instance of debugbar
        ->captureAjax(true)         //(optional) To send data in headers in ajax
];

Delay

Delays the response to simulate slow bandwidth in local environments. You can use a number or an array to generate random values in seconds.

use Psr7Middlewares\Middleware;

$middlewares = [

    Middleware::delay(3.5),      //delay the response 3.5 seconds

    Middleware::delay([1, 2.5]), //delay the response between 1 and 1.5 seconds
];

DetectDevice

Uses Mobile-Detect library to detect the client device.

use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\DetectDevice;

$middlewares = [

    Middleware::DetectDevice(),

    function ($request, $response, $next) {
        //Get the device info
        $device = DetectDevice::getDevice($request);

        if ($device->isMobile()) {
            //mobile stuff
        }
        elseif ($device->isTablet()) {
            //tablet stuff
        }
        elseif ($device->is('bot')) {
            //bot stuff
        }

        return $next($request, $response);
    },
];

DigestAuthentication

Implements the digest http authentication. You have to provide an array with the users and password:

use Psr7Middlewares\Middleware;

$middlewares = [

    Middleware::DigestAuthentication([
            'username1' => 'password1',
            'username2' => 'password2'
        ])
        ->realm('My realm') //(optional) custom realm value
        ->nonce(uniqid()),   //(optional) custom nonce value

    function ($request, $response, $next) {
        $username = DigestAuthentication::getUsername($request);

        return $next($request, $response);
    }
];

EncodingNegotiator

Uses willdurand/Negotiation (2.x) to detect and negotiate the encoding type of the document.

use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\EncodingNegotiator;

$middlewares = [

    Middleware::EncodingNegotiator()
        ->encodings(['gzip', 'deflate']), //(optional) configure the supported encoding types

    function ($request, $response, $next) {
        //get the encoding (for example: gzip)
        $encoding = EncodingNegotiator::getEncoding($request);

        return $next($request, $response);
    }
];

ErrorHandler

Executes a handler if the response returned by the next middlewares has any error (status code 400-599). You can catch also the exceptions throwed.

…

FastRoute

To use FastRoute as middleware.

use Psr7Middlewares\Middleware;

$router = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {

    $r->addRoute('GET', '/blog/{id:[0-9]+}', function ($request, $response, $app) {
        return 'This is the post number'.$request->getAttribute('id');
    });
});

$middlewares = [

    Middleware::FastRoute($router) //Instance of FastRoute\Dispatcher
        ->argument($myApp)         //(optional) arguments appended to the controller
];

Firewall

Uses M6Web/Firewall to provide an IP filtering. This middleware depends on ClientIp (to extract the ips from the headers).

See the ip formats allowed for trusted/untrusted options:

use Psr7Middlewares\Middleware;

$middlewares = [

    //required to capture the user ips before
    Middleware::ClientIp(),

    //set the firewall
    Middleware::Firewall()
        ->trusted(['123.0.0.*'])   //(optional) i

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPhttpmiddlewarepsr-7

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言