Send well-chosen response headers before output to reduce browser attack surfaces. The examples separate the essential operation from the conditions a production implementation must enforce.
What It Does
Send well-chosen response headers before output to reduce browser attack surfaces.
Prerequisites
Use a dedicated development environment with test accounts and records. Separate authorization, validation and error handling from response formatting; never copy demonstration-only secrets into production.
Example 1: Core Behavior
The first example isolates the core operation so its result is easy to understand.
<?php
header("Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'");
header('X-Content-Type-Options: nosniff');
echo 'Headers queued';
Example 2: Alternative or Failure Case
The second example demonstrates an alternative outcome, rule or failure condition.
<?php
header('Referrer-Policy: strict-origin-when-cross-origin');
header('X-Frame-Options: DENY');
echo 'Document protection headers queued';
Practical Example: Applying the Rule
The practical example shows how to carry the same constraint into application code.
<?php
header('Strict-Transport-Security: max-age=31536000');
// HSTS should be sent only from HTTPS responses on a fully HTTPS-capable site.
echo 'HSTS queued';
Important Behavior and Edge Cases
CSP directives need testing because they can break legitimate scripts and are not a substitute for output encoding.
Comparison with Related Functions or Patterns
| Approach | When it differs |
|---|---|
| Using Security Headers in PHP | Send well-chosen response headers before output to reduce browser attack surfaces. |
| Related API or pattern | HttpOnly and Secure cookies protect different surfaces than Content Security Policy. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Deploying a CSP without checking how actual scripts load | CSP directives need testing because they can break legitimate scripts and are not a substitute for output encoding. |
| Substituting a related API without checking its semantics | HttpOnly and Secure cookies protect different surfaces than Content Security Policy. |
Key Takeaways
- Send well-chosen response headers before output to reduce browser attack surfaces.
- CSP directives need testing because they can break legitimate scripts and are not a substitute for output encoding.
- HttpOnly and Secure cookies protect different surfaces than Content Security Policy.
Select this API or pattern based on its documented behavior and the trust boundaries in your own application, and test all external integrations against their actual deployments.