DEV Community

Cover image for Content Security Policy with PHP

Posted on

Content Security Policy with PHP

Use X-Frame-Options and Content-Security-Policy with PHP

Most of today's browsers can help protect your site from malicious attacks if you tell them so. A method that is almost universally supported is to set the X-Frame options. If this option is set, the browser does not allow other sites to display your own site in an iframe. This protects against clickjacking attacks and should be used on all sensitive pages such as the login page.

// Adds X-Frame-Options to HTTP header so that page can only be shown in an iframe of the same site.
header('X-Frame-Options: SAMEORIGIN'); // FF 3.6.9+ Chrome 4.1+ IE 8+ Safari 4+ Opera 10.5+

Enter fullscreen mode Exit fullscreen mode

Users who work with a current browser automatically benefit when a website sends a Content Security Policy (CSP) in the header. With a CSP, you can define where JavaScript code is accepted from, which pages are allowed to display your page in an iframe, and many other things. If a browser supports CSP, this can be effective protection against cross-site scripting. more…

The implementation in PHP is very simple, but problems can arise with inline JavaScript. You get the greatest protection if you avoid all JavaScript in the HTML files and instead store them in separate *.js files. In case this is not possible (existing source code), there is an option to allow inline-script.

// Adds the Content-Security-Policy to the HTTP header.
// JavaScript will be restricted to the same domain as the page itself.
header("Content-Security-Policy: default-src 'self'; script-src 'self';"); // FF 23+ Chrome 25+ Safari 7+ Opera 19+
header("X-Content-Security-Policy: default-src 'self'; script-src 'self';"); // IE 10+

Enter fullscreen mode Exit fullscreen mode

Top comments (0)