PHP Luminova: Content Security Policy
Luminova’s Content Security Policy guide covers resource directives, nonces and hashes for inline code, and violation reporting.
A Content Security Policy (CSP) tells the browser which sources a page may load scripts, styles, images, and other resources from. The policy can also permit specific inline scripts or styles by matching a nonce or hash.
An enforcing policy blocks resources that violate its directives. A report-only policy allows the browser to report violations while the page continues to load.
Examples
Build a Policy from Directives
A policy is a list of directives separated by semicolons. This example allows resources from the same origin by default and permits scripts from one additional host.
$directives = [
"default-src 'self'",
"script-src 'self' https://scripts.example.com",
"object-src 'none'",
];
header('Content-Security-Policy: ' . implode('; ', $directives));Generate Nonces for Inline Scripts and Styles
Generate fresh values for each response and include them in both the HTTP policy and the matching elements in your template.
use Luminova\Security\CSP;
$scriptNonce = CSP::randomNonce(32);
$styleNonce = CSP::randomNonce(32);
header(
"Content-Security-Policy: default-src 'self'; "
. "script-src 'self' 'nonce-{$scriptNonce}'; "
. "style-src 'self' 'nonce-{$styleNonce}'"
);Using Nonces in Templates
Just print the nonce where the inline code lives.
<style nonce="<?= $styleNonce; ?>">
body { background: #f5f5f5; }
</style>
<script nonce="<?= $scriptNonce; ?>">
console.log("Inline script executed safely with CSP nonce");
</script>Note:
- One nonce per directive per request.
- If the nonce is missing or wrong, the browser blocks the code.
- Works best when templates are rendered server-side.
Using Hashes for Inline Scripts
Compute the hash from the exact inline script that the browser will receive. Send the quoted hash source in the HTTP policy before rendering the script.
$script = 'console.log("Hello World");';
$hash = base64_encode(hash('sha256', $script, true));
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-{$hash}'");Render the same trusted script text inside the script element. Whitespace changes require a new digest. Use the nonce example above when the script changes between responses. See the Content Security Policy source expression syntax.
Nonce vs Hash (Quick Comparison)
| Use Case | Choose |
|---|---|
| Dynamic pages | Nonce |
| Static inline script | Hash |
| Per-request security | Nonce |
| Long-term caching | Hash |
- Nonces are simpler to implement and provide strong security for most applications.
- Hashes offer precise control but require strict matching and careful maintenance.
'unsafe-inline'should be avoided in production environments and used only for testing or demonstration purposes.
Securing a Webpage with CSP
This example shows how to secure a page using Content Security Policy (CSP) in an HTTP controller.
What this setup does:
- Inline scripts and styles use generated nonces.
- The browser blocks any script or style not allowed by CSP.
- Use the report-only HTTP header to collect violations before enforcing a policy.
Controller Example
namespace App\Controllers\Http;
use Luminova\Security\CSP;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use Luminova\Base\Http\AbstractController;
#[Prefix('/dashboard/(:base)')]
class DashboardController extends AbstractController
{
#[Route('/dashboard/', methods: ['GET'])]
public function dashboard(): int
{
$scriptNonce = CSP::randomNonce(32);
$styleNonce = CSP::randomNonce(32);
$this->tpl->headers([
'Content-Security-Policy' => "default-src 'self'; "
. "script-src 'self' https://cdn.example.com 'nonce-{$scriptNonce}'; "
. "style-src 'self' 'nonce-{$styleNonce}'",
]);
return $this->view('dashboard', [
'scriptNonce' => $scriptNonce,
'styleNonce' => $styleNonce,
]);
}
}Notes for beginners:
- CSP is created once per request.
- Nonces are generated automatically.
- The CSP header is queue for rendering the page template.
- The CSP object is passed to the template so nonces can be reused safely.
Using CSP in Templates
Inline scripts and styles must include the correct nonce or the browser will block them.
Template file:/resources/Views/dashboard.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<!-- Inline style with nonce -->
<style nonce="<?= $styleNonce; ?>">
body {
background-color: #f5f5f5;
font-family: Arial, sans-serif;
}
h1 {
color: #333;
}
</style>
<!-- External stylesheet -->
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:400,700">
</head>
<body>
<h1>Welcome to the Dashboard</h1>
<!-- Inline script with nonce -->
<script nonce="<?= $scriptNonce; ?>">
console.log('Dashboard inline script executed safely');
</script>
<!-- External script -->
<script src="https://cdn.example.com/dashboard.js"></script>
</body>
</html>Add Report-Only Headers to a Response
A report-only policy asks the browser to report violations without blocking resources. This example shows how to attach the reporting headers to a Luminova response. To monitor an HTML page, attach the policy to the response that serves the page.
API Controller Example
namespace App\Controllers\Http;
use function Luminova\Funcs\response;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use Luminova\Base\Http\AbstractController;
#[Prefix('/api/(:base)')]
class RestController extends AbstractController
{
#[Route('/api/list', methods: ['GET'])]
public function list(): int
{
$headers = [
'Content-Security-Policy-Report-Only' => "default-src 'self'; "
. 'report-uri https://example.com/csp/report; report-to csp-group',
'Reporting-Endpoints' => 'csp-group="https://example.com/csp/report"',
];
return response(headers: $headers)->json([
'status' => 'success',
'message' => 'API response with a report-only CSP',
]);
}
}How This Works
- The CSP header is sent with the API response.
- Browsers do not block anything in report-only mode.
- Any policy violation is reported to the configured endpoint.
- API consumers continue working normally.
Report-only mode allows you to review browser reports before turning on enforcement.
Configuring a CSP Reporting Endpoint
A CSP reporting endpoint is just a normal HTTP endpoint that accepts POST requests containing JSON.Browsers send CSP violations there automatically.
Create a Reporting Endpoint (Controller)
This endpoint receives violation reports from the browser.
namespace App\Controllers\Http;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use function Luminova\Funcs\logger;
use Luminova\Base\Http\AbstractController;
#[Prefix('/csp/(:base)')]
class CspReportController extends AbstractController
{
#[Route('/csp/report', methods: ['POST'])]
public function report(): int
{
$raw = $this->request->getRaw();
$report = $raw === null ? null : json_decode($raw, true);
if (!is_array($report)) {
http_response_code(400);
return STATUS_SUCCESS;
}
// Record receipt without logging URLs or other submitted values.
logger('debug', 'CSP violation report received.');
http_response_code(204);
return STATUS_SUCCESS;
}
}If reporting is enabled, browsers send violations as a JSON POSTto your configured reporting endpoint.
Example violation payload:
{
"csp-report": {
"document-uri": "https://example.com/page",
"blocked-uri": "https://evil.com/script.js",
"violated-directive": "script-src 'self'",
"original-policy": "default-src 'self'; script-src 'self'"
}
}Note:
- Must accept POST
- Must accept JSON
- Response body is ignored (204 is ideal)
- Do not throw errors here — browsers will retry
Class Definition
- Full namespace:
Luminova\Security\CSP
Methods
__construct
Create a policy builder.
public function __construct(private bool $reportOnly = false)Parameters:
| Parameter | Type | Description |
|---|---|---|
$reportOnly | bool | Select the report-only HTTP header. Defaults to false. |
randomNonce
Generate a Base64 value from random bytes and prepend an optional prefix.
public static final function randomNonce(int $length = 16, string $prefix = ''): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$length | int | Size parameter. The generator uses ceil($length / 2) random bytes. |
$prefix | string | Optional prefix. Defaults to an empty string. |
Return:
string - A newly generated value.
getNonce
Read the nonce registered for a directive.
public function getNonce(string $directive): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
Return:
?string - The nonce or null.
getHash
Read the digest registered for a directive.
public function getHash(string $directive): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
Return:
?string - The Base64 digest or null.
get
Read a directive’s source expressions.
public function get(string $directive): ?arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
Return:
string[]|null - The configured values or null.
toArray
Inspect a directive and its stored nonce and digest.
public function toArray(string $directive): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
Return:
array{directive:?array,nonce:?string,hash:?string} - The directive details.
| Key | Type | Description |
|---|---|---|
directive | string[]|null | Configured source expressions. |
nonce | string|null | Registered nonce. |
hash | string|null | Registered Base64 digest. |
add
Append values to a directive. The builder removes duplicate values when it serializes the policy.
public function add(string $directive, array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
addNonce
Append a nonce source. Use the same nonce on the inline element for this response.
public function addNonce(string $directive, ?string $nonce = null, int $length = 16): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
$nonce | ?string | Nonce to register, or null to generate one. |
$length | int | Size parameter passed to randomNonce(). Defaults to 16. |
Return:
self - The current policy builder.
addHash
Register a Base64 digest in the builder. For a policy with a browser-compatible quoted hash source, see Using Hashes for Inline Scripts.
public function addHash(string $directive, string $algo, ?string $hash = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
$algo | string | Digest algorithm, such as sha256. |
$hash | ?string | Base64 digest. A generated digest is unrelated to the content. |
Return:
self - The current policy builder.
reportOnly
Choose report-only or enforcing mode for HTTP headers.
public function reportOnly(bool $enable = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$enable | bool | Enable report-only mode. Defaults to true. |
Return:
self - The current policy builder.
remove
Remove a directive and its stored nonce and hash.
public function remove(string $directive): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$directive | string | Directive name, such as script-src. |
Return:
self - The current policy builder.
clear
Remove all configured directives and tokens.
public function clear(): selfReturn:
self - The current policy builder.
build
Serialize the directives into a policy value.
public function build(): stringReturn:
string - The policy value.
getMetaTag
Render a meta element for an enforcing policy. Use HTTP headers for report-only policies.
public function getMetaTag(string $id = ''): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string | Optional element ID. |
Return:
string - The escaped HTML markup.
getHeaders
Build the policy header and any reporting endpoint header.
public function getHeaders(): arrayReturn:
array<string,string> - Header names mapped to their values.
sendHeader
Send the policy headers before writing the response body.
public function sendHeader(): voiddefaultSrc
Append source expressions to the default-src directive.
public function defaultSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
scriptSrc
Append source expressions to the script-src directive.
public function scriptSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
styleSrc
Append source expressions to the style-src directive.
public function styleSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
imgSrc
Append source expressions to the img-src directive.
public function imgSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
connectSrc
Append source expressions to the connect-src directive.
public function connectSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
fontSrc
Append source expressions to the font-src directive.
public function fontSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
mediaSrc
Append source expressions to the media-src directive.
public function mediaSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
objectSrc
Append source expressions to the object-src directive.
public function objectSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
frameSrc
Append source expressions to the frame-src directive.
public function frameSrc(array|string $values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$values | string|string[] | One source expression or an array of source expressions. |
Return:
self - The current policy builder.
reportUri
Register a legacy violation-report destination.
public function reportUri(string $uri): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$uri | string | Report destination URI. |
Return:
self - The current policy builder.
reportTo
Register a reporting group and add its URL to the Reporting-Endpoints header.
public function reportTo(string $group, string $endpoint): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$group | string | Reporting group name. |
$endpoint | string | Report destination URL. |
Return:
self - The current policy builder.