Download the PHP package oscarotero/psr7-middlewares without Composer
On this page you can find all versions of the php package oscarotero/psr7-middlewares. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download oscarotero/psr7-middlewares
More information about oscarotero/psr7-middlewares
Files in oscarotero/psr7-middlewares
Package psr7-middlewares
Short Description Collection of HTTP middlewares compatible with PSR-7
License MIT
Homepage https://github.com/oscarotero/psr7-middlewares
Informations about the package psr7-middlewares
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:
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.
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:
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.
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.
BasicAuthentication
Implements the basic http authentication. You have to provide an array with all users and password:
BlockSpam
To block referral spam using the piwik/referrer-spam-blacklist 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.
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.
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.
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.
DetectDevice
Uses Mobile-Detect library to detect the client device.
DigestAuthentication
Implements the digest http authentication. You have to provide an array with the users and password:
EncodingNegotiator
Uses willdurand/Negotiation (2.x) to detect and negotiate the encoding type of the document.
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.
Expires
Adds Expires
and max-age
directive of the Cache-Control
header in the response. It's similar to the apache module mod_expires. By default uses the same configuration than h5bp apache configuration. Useful for static files.
FastRoute
To use FastRoute as middleware.
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:
FormatNegotiator
Uses willdurand/Negotiation (2.x) to detect and negotiate the format of the document using the url extension and/or the Accept
http header. It also adds the Content-Type
header to the response if it's missing.
You can optionally specify the formats which your server supports, in priority order, with the first element being the default.
If the client requests a format which is not supported by the server, then the default format will be used. If you wish to generate a 406 Not Acceptable response instead, set the default format to null.
FormTimestamp
Simple spam protection based on injecting a hidden input in all post forms with the current timestamp. On submit the form, check the time value. If it's less than (for example) 3 seconds ago, assumes it's a bot, so returns a 403 response. You can also set a max number of seconds before the form expires.
Geolocate
Uses Geocoder library to geolocate the client using the ip. This middleware depends on ClientIp (to extract the ips from the headers).
GoogleAnalytics
Inject the Google Analytics code in all html pages.
Gzip
Use gzip functions to compress the response body, inserting also the Content-Encoding
header.
Honeypot
Implements a honeypot spam prevention. This technique is based on creating a input field that should be invisible and left empty by real users but filled by most spam bots. The middleware scans the html code and inserts this inputs in all post forms and check in the incoming requests whether this value exists and is empty (is a real user) or doesn't exist or has a value (is a bot) returning a 403 response.
Https
Returns a redirection to the https scheme if the request uri is http. It also adds the Strict Transport Security header to protect against protocol downgrade attacks and cookie hijacking.
ImageTransformer
Uses imagecow/imagecow 2.x to transform images on demand. You can resize, crop, rotate and convert to other formats. Use the the imagecow syntax to define the available sizes.
To define the available sizes, you have to asign a filename prefix representing the size, so any file requested with this prefix will be dinamically transformed.
There's also support for Client hints to avoid to serve images larger than needed (currently supported only in chrome and opera).
If you want to save the transformed images in the cache, provide a library compatible with psr-6 for that.
IncludeResponse
Useful to include old style applications, in which each page has it's own php file. For example, let's say we have an application with paths like /about-us.php
or /about-us
(resolved to /about-us/index.php
), this middleware gets the php file, include it safely, capture the output and the headers send and create a response with the results. If the file does not exits, returns a 404
response (unless continueOnError
is true).
JsonValidator
Uses justinrainbow/json-schema to validate an application/json
request body with a JSON schema:
JsonSchema
Uses justinrainbow/json-schema to validate an application/json
request body using route-matched JSON schemas:
LanguageNegotiation
Uses willdurand/Negotiation to detect and negotiate the client language using the Accept-Language header and (optionally) the uri's path. You must provide an array with all available languages:
LeagueRoute
To use league/route (2.x) as a middleware:
MethodOverride
Overrides the request method using the X-Http-Method-Override
header. This is useful for clients unable to send other methods than GET and POST:
Minify
Uses mrclay/minify to minify the html, css and js code from the responses.
Payload
Parses the body of the request if it's not parsed and the method is POST, PUT or DELETE. It has support for json, csv and url encoded format.
PhpSession
Initializes a php session using the request data.
Piwik
To use the Piwik analytics platform. Injects the javascript code just before the </body>
closing tag.
ReadResponse
Read the response content from a file. It's the opposite of SaveResponse. The option continueOnError
changes the behaviour of the middleware to continue with the next middleware if the response file is NOT found and returns directly the response if the file is found. This is useful to use the middleware as a file based cache and add a router middleware (or other readResponses) next in the queue.
Recaptcha
To use the google recaptcha library for spam prevention.
Rename
Renames the request path. This is useful in some use cases:
- To rename public paths with random suffixes for security reasons, for example the path
/admin
to a more unpredictible/admin-19640983
- Create pretty urls without use any router. For example to access to the path
/static-pages/about-me.php
under the more friendly/about-me
Note that the original path wont be publicly accesible. On above examples, requests to /admin
or /static-pages/about-me.php
returns 404 responses.
ResponseTime
Calculates the response time (in miliseconds) and saves it into X-Response-Time
header:
Robots
Disables the robots of the search engines for non-production environment. Adds automatically the header X-Robots-Tag: noindex, nofollow, noarchive
in all responses and returns a default body for /robots.txt
request.
SaveResponse
Saves the response content into a file if all of the following conditions are met:
- The method is
GET
- The status code is
200
- The
Cache-Control
header does not containno-cache
value - The request has not query parameters.
This is useful for cache purposes
Shutdown
Useful to display a 503 maintenance page. You need to specify a handler.
TrailingSlash
Removes (or adds) the trailing slash of the path. For example, /post/23/
will be converted to /post/23
. If the path is /
it won't be converted. Useful if you have problems with the router.
Uuid
Uses ramsey/uuid (3.x) to generate an Uuid (Universally Unique Identifiers) for each request (compatible with RFC 4122 versions 1, 3, 4 and 5). It's usefull for debugging purposes.
Whoops
To use whoops 2.x as error handler.
Www
Adds or removes the www
subdomain in the host uri and, optionally, returns a redirect response. The following types of host values wont be changed:
- The one word hosts, for example:
http://localhost
. - The ip based hosts, for example:
http://0.0.0.0
. - The multi domain hosts, for example:
http://subdomain.example.com
.
Lazy/conditional middleware creation
You may want to create middleware in a lazy way under some circunstances:
- The middleware is needed only in a specific context (for example in development environments)
- The middleware creation is expensive and is not needed always (because a previous middleware returns a cached response)
- The middleware is needed only in a specific path
To handle with this, you can use the Middleware::create()
method that must return a callable or false. Example:
Extending middlewares
Some middleware pieces use different functions to change the http messages, depending of some circunstances. For example, Gzip that depending of the Accept-Encoding
header, use a different method to compress the response body.
The interface Psr7Middlewares\Transformers\ResolverInterface
provides a way to resolve and returns the apropiate "transformer" in each case. The transformer is just a callable with a specific signature. You can create custom resolvers or extend the included in this package to add your owns. Let's see an example:
The following middlewares are using resolvers that you can customize:
- Payload To parse the body according with the format (json, urlencoded, csv, ...)
- Gzip To encode the body with the encoding method supported by the browser (gzip, deflate)
- Minify To use different minifiers for each format (html, css, js, ...)
Contribution
New middlewares are appreciated. Just create a pull request.