Add a Content Security Policy(CSP) to your Web Site with PHP
What is Content Security Policy(CSP)?
Content Security Policy(CSP) is a mechanism in the browser that restricts what content will be requested and run by the browser. CSP does this by passing in a specific response header that tells the browser what resources (images, javascript, css, frames, etc) can be requested and accepted to execute. There are multiple ways to setup CSP for your web site, you can use your web server configuration like I showed in a previous example or use a dynamic scripting language like PHP.
Why use PHP to create your Content Security Policy
- Creating CSP in PHP is extremely dynamic and easy to setup per page policies.
- Putting CSP in web server’s configuration or .htaccess file is typically all or nothing.
- Working with a web server’s Directory and File rules are much more cumbersome and difficult to gain the same level of flexibility as PHP.
Difference between the two CSP Headers
- X-Content-Security-Policy executes only what is in the policy. So if you’re not careful, you could be blocking legitimate resources. If you’re new to CSP, start with the report mode header.
- X-Content-Security-Policy-Report-Only executes all resources and mainly used to ease your way into CSP by reporting (but not stopping) violating resources.
So, lets see some examples!
Examples of Content Security Policy(CSP) in PHP
Only content from your own domain is allowed.
<?php
header("X-Content-Security-Policy: allow 'self'");
?>
Only content from your own domain and javascript from www.google-analytics.com is acceptable. Anything outside of that will be executed but also a report will be sent back to your domain’s voilation.php.
<?php
header("X-Content-Security-Policy-Report-Only: allow 'self'; script-src www.google-analytics.com; report-uri /violation.php");
?>
Important Links
Documentation of PHP’s Header function
Mozilla’s CSP Definition
