Content Security Policy (CSP)
Examples


CSP PHP Example

Here's how to use PHP to add a Content-Security-Policy HTTP response header to your site.

Example CSP Header with PHP

By using the PHP header() function we can

<?php
	header("Content-Security-Policy: default-src 'self'");
?>

The php header function simply takes the full value of the header we want to set Header-Name: value.

If all is working properly, when your hit your php page, you should now have the following show up in the HTTP response headers:

Content-Security-Policy: default-src 'self'

What goes inside a CSP policy?

If you're not sure what default-src 'self'; means, then check out the Content Security Policy reference for details. Or you can take a look at more CSP examples, if you prefer to learn by example.

Another Option for PHP

Another option is to use a web server mechanism to add a HTTP response header, such as a htaccess file. The advantage of using the web server to add the CSP header is that it can apply to all requests, not just your php files.

You may however want to use PHP to set the header if you will have different policies for different php pages, or if you use certain features such as a CSP nonce, which require a random token to be uniquely generated for each request.

The browser doesn't care if you add the Content-Security-Policy header with PHP, or with your web server - just make sure you add it one way or another.

CSP Developer Field Guide

CSP Developer Field Guide

Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.

Grab a Copy

Struggling to stay on top of security advisories?

Advisory Week is a weekly roundup of all the security advisories published by the major software vendors.