PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
174: Content Security Policy Headers in PHP
A few years ago, I was reviewing a PR for a junior dev who had built a sleek user dashboard. He’d been diligent about using htmlspecialchars() on all user-generated output, so he felt safe. But during my audit, I found a tiny hole: a profile field that allowed a specific set of HTML tags for formatting. I managed to inject a simple <img src=x onerror="alert('Hacked')"> tag. Because the onerror attribute executes JavaScript directly in the browser, his output encoding didn't stop it. That's when I sat him down and explained that while input sanitization is vital, you need a second line of defense that lives in the browser itself. That's where Content Security Policy (CSP) comes in.
Defining Your Trust Boundaries
A Content Security Policy is essentially a set of instructions you send to the browser via an HTTP header. It tells the browser, "I only trust scripts from these specific domains, and I don't trust any inline scripts unless I explicitly sign off on them." If a hacker manages to inject a script tag pointing to a malicious server, the browser will check your CSP, see that the server isn't on the whitelist, and simply refuse to execute the code. It's a massive safety net.
In PHP, you implement this using the header() function. You want to send this before any HTML is rendered. Here is a basic example of a restrictive policy:
<?php
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://trustedscripts.com; style-src 'self' https://fonts.googleapis.com;");
?>
Let's break that down. default-src 'self' is your fallback; it tells the browser that by default, images, fonts, and AJAX requests should only come from your own domain. script-src 'self' https://trustedscripts.com expands that specifically for JavaScript, allowing your own files and one external trusted source. Notice the single quotes around 'self'—that's a keyword, not a string, so the quotes are mandatory.
Handling Inline Scripts with Nonces
Here is the catch: a strict CSP blocks all inline scripts (like <script>alert('hi')</script>) and all inline event handlers (like onclick). While you should generally move your JS to external files, sometimes you just need a small bit of PHP-generated data available to a script on the page. You can't just use 'unsafe-inline' because that completely defeats the purpose of having a CSP—it's basically like leaving the front door unlocked because you're too lazy to find your keys.
The professional way to handle this is with a nonce (a "number used once"). You generate a cryptographically strong random string on every single page load, include it in your CSP header, and then add that same string as an attribute to your script tag. If the nonces match, the browser trusts the script.
<?php
// Generate a random nonce for this request
$nonce = base64_encode(random_bytes(16));
// Add the nonce to the CSP header
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-$nonce';");
?>
<script nonce="<?php echo $nonce; ?>">
console.log("This inline script is allowed because the nonce matches!");
</script>
<script>
alert("I will be blocked by the browser!");
</script>
I've found that using nonces is the only way to maintain a high security posture without breaking your site's functionality. It forces you to be intentional about which scripts are actually running on your pages.
📋 Practical Task
Implementing a Nonce-Based CSP for a User Settings Page
You are tasked with securing a settings.php page. The page displays user settings and requires one specific inline script to initialize a JavaScript object with the current user's ID from PHP.
- Create a PHP file that generates a cryptographically secure nonce.
- Send a
Content-Security-Policyheader that:- Sets
default-srcto'self'. - Allows scripts from
'self'and allows inline scripts that possess the correctnonce. - Allows styles from
'self'andhttps://cdn.example.com.
- Sets
- Include one
<script>tag that uses the nonce to successfully print "User ID initialized" to the console. - Include a second
<script>tag without a nonce that attempts to alert "I am a malicious script!". - Verify in your browser's developer console (F12) that the second script was blocked by the CSP while the first one executed.
There are no comments for now.