RealWorldDevelopers
11/23/2017 - 2:51 AM

CSP headers in PHP

CSP headers in PHP

	
	
 	  
 <?php 
  // return json safe
	header('Content-type: application/json');
  echo json_encode($data, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_APOS | JSON_HEX_AMP);
	?>
	
	
**************

<?php
	// headers
	if (isset($_GET['setHeader']) && $_GET['setHeader'] === '1') {
		header('X-FRAME-OPTIONS: DENY');	// if you use frames  else just this line
	}
	
	// CSP
	$nonce = uniqid();
	header("Content-Security-Policy: default-src 'self' 'nonce-$nonce'");
	
	header('X-Content-Type-Options: nosniff');
	header("X-XSS-Protection: 1");
	
	
	
	
	
	*** actual **
	$nonce = uniqid();
	$headerValue  = "default-src 'none'; ";
	$headerValue .= "font-src 'self' https://cdnjs.cloudflare.com https://*.gstatic.com https://maxcdn.bootstrapcdn.com; ";
	$headerValue .= "script-src 'self' 'unsafe-inline' 'unsafe-eval' *.facebook.net https://*.google.com https://*.googleapis.com https://*.gstatic.com https://cdnjs.cloudflare.com; ";
	$headerValue .= "style-src 'self' 'unsafe-inline' http://www.w3schools.com https://cdnjs.cloudflare.com https://*.googleapis.com https://maxcdn.bootstrapcdn.com; ";
	$headerValue .= "img-src 'self' data: *.facebook.com; ";
	$headerValue .= "frame-src 'self' *.facebook.com *.google.com; ";
	header("Content-Security-Policy: ". $headerValue );
	header('X-FRAME-OPTIONS: DENY');
	header('X-Content-Type-Options: nosniff');
	header("X-XSS-Protection: 1");
	
	
	

?>

<html>
  <head>
    <title>CSP</title>
	<script nonce="<?php echo $nonce; ?>">
	alert(1);
	</script>
  </head>
  <body>
    <ul style="color: orange;">
	  <li>Item 1</li>
	  <li>Item 2</li>
	</ul>
  </body>
</html>

*****************


<?php
	// token validation
  /* 
	  if random_bytes() is not available (PHP < 7), use userland 
	  implementation from https://github.com/paragonie/random_compat
	*/
	
	if (isset($_POST['btn'])) {
		if (isset($_POST['_csrfname']) && isset($_POST['_csrfvalue']) &&
		    isset($_SESSION[$_POST['_csrfname']]) && 
			$_SESSION[$_POST['_csrfname']] === $_POST['_csrfvalue'] && 
			$_POST['_csrfvalue'] !== '') {
				echo '<h1>Item purchased</h1>';
		} else {
			throw new Exception('CSRF token validation failed');
		}
	}
		$name = 'token-' . mt_rand();
    $token = bin2hex(random_bytes(32));
    $_SESSION[$name] = $token;	
?>
	<form action="" method="post">	
	  <input type="hidden" name="_csrfname" value="<?php echo $name; ?>">
    <input type="hidden" name="_csrfvalue" value="<?php echo $token; ?>">		   
		<input name="btn" type="submit" value="Buy!">
	</form>