PHP Classes

File: examples/example6.php

Recommend this page to a friend!
  Classes of Tom Postma   PHP Content Security Policy generator   examples/example6.php   Download  
File: examples/example6.php
Role: Example script
Content type: text/plain
Description: Example: how to calculate and use a hash code to allow inline JavaScript/ECMAScript.
Class: PHP Content Security Policy generator
Generate CSP headers to prevent security attacks
Author: By
Last change: Update examples, in examples 2 and 6 the resources are only loaded over https.

Signed-off-by: Tom <>
Added support for sending the Referrer-Policy http header base on the current referrerpolicy value and added strict-origin-when-cross-origin and strict-origin values.

Signed-off-by: Tom <>
Date: 5 years ago
Size: 1,511 bytes


Class file image Download

// E.g. allow inline google analytics javascript snippet.
// The following javascript code needs hashed before the Content Security Policy
// HTTP header is send to the client.
$jscode = "
window['ga-disable-UA-XXXXX-Y'] = true;
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
ga('create', 'UA-XXXXX-Y', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');

  alert('The (disabled)Google analytics snippet loaded.');

CSPGenerator::getInstance()->addScriptsrcHash($jscode, 'sha384');

// Set the headers, always call this method before any content output.
// Start content output.
?><!DOCTYPE html>
        <meta charset="UTF-8">
        <title>example6 - allow inline script with hash</title>
    <!-- Whitelisted inline script: -->
    <script type="application/javascript"><?php echo $jscode; ?></script>
    <!-- Not whitelisted inline script: -->
    <script type="application/javascript">
alert('This should not popup.');
    See page sourcecode.