PHP Classes

File: examples/example4.php

Recommend this page to a friend!
  Classes of Tom Postma   PHP Content Security Policy generator   examples/example4.php   Download  
File: examples/example4.php
Role: Example script
Content type: text/plain
Description: Example: how to use a nonce to allow inline javascript/ECMAScript in page.
Class: PHP Content Security Policy generator
Generate CSP headers to prevent security attacks
Author: By
Last change: Example: how to use a nonce to allow inline javascript/ECMAScript in page.
Date: 8 years ago
Size: 1,085 bytes
 

Contents

Class file image Download
<?php
require_once('../CSPGenerator.php');

// Allow use of some inline JavaScript by the use of nonces.
CSPGenerator::getInstance()->setScriptsrcNonce();


// Set the headers, always call this method before any content output.
CSPGenerator::getInstance()->Parse();
// Start content output.
?><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>example4 - allow inline JavaScript with nonce</title>
    </head>
    <body>
        <div id="result"><noscript>JavaScript not enabled.</noscript></div>
        <script type="application/javascript" nonce="<?php echo CSPGenerator::getInstance()->getScriptsrcNonce(); ?>">
document.getElementById('result').textContent = 'okay, whitelisted inline script loaded.';
        </script>
        <script type="application/javascript" nonce="deliberately_invalid_nonce_here">
document.getElementById('result').textContent = 'bad, inline script with invalid nonce is not blocked.';
        </script>
        <script type="application/javascript">
document.getElementById('result').textContent = 'bad, inline script without a nonce is not blocked.';
        </script>
    </body>
</html>