FyreCSP is a free, open-source content security policy library for PHP.
Using Composer
composer require fyre/csp
In PHP:
use Fyre\Security\CspBuilder;
Add Headers
Add CSP headers to a ClientResponse.
$response
is a ClientResponse.
$newResponse = CspBuilder::addHeaders($response);
Clear
Clear all policies.
CspBuilder::clear();
Create Policy
Create a Policy.
$key
is a string representing the policy key, and should be one of eitherCspBuilder::DEFAULT
orCspBuilder::REPORT
.$directives
is an array containing the directives to add, and will default to [].
CspBuilder::createPolicy($key, $directives);
Get Policy
Get a Policy.
$key
is a string representing the policy key, and should be one of eitherCspBuilder::DEFAULT
orCspBuilder::REPORT
.
$policy = CspBuilder::getPolicy($key);
Get Policies
Get all policies.
$policies = CspBuilder::getPolicies();
Get Report To
Get the Report-To values.
$reportTo = CspBuilder::getReportTo();
Has Policy
Check if a policy exists.
$key
is a string representing the policy key, and should be one of eitherCspBuilder::DEFAULT
orCspBuilder::REPORT
.
$hasPolicy = CspBuilder::hasPolicy($key);
Set Policy
Set a policy.
$key
is a string representing the policy key, and should be one of eitherCspBuilder::DEFAULT
orCspBuilder::REPORT
.$policy
is a Policy.
CspBuilder::setPolicy($key, $policy);
Set Report To
Set the Report-To values.
$reportTo
is an array containing the Report-To values.
CspBuilder::setReportTo($reportTo);
Add Directive
Add options to a directive.
$directive
is a string representing the directive.$value
is a string, or an array of strings containing the values to add. For directives that don't require values, you can set this to true or false indicating whether to include the directive.
$newPolicy = $policy->addDirective($directive, $value);
Get Directive
Get the options for a directive.
$directive
is a string representing the directive.
$options = $policy->getDirective($directive);
Get Header
Get the header string.
$header = $policy->getHeader();
Has Directive
Determine if a directive exists.
$directive
is a string representing the directive.
$hasDirective = $policy->hasDirective($directive);
Remove Directive
Remove a directive.
$directive
is a string representing the directive.
$newPolicy = $policy->removeDirective($directive);
use Fyre\Security\Middleware\CspMiddleware;
$options
is an array containing options for the middleware.default
is an array containing the policy directives, and will default to [].report
is an array containing the report-only directives, and will default to null.reportTo
is an array containing the Report-To header value, and will default to [].
$middleware = new CspMiddleware($options);
Process
$request
is a ServerRequest.$handler
is a RequestHandler.
$response = $middleware->process($request, $handler);
This method will return a ClientResponse.