Knowledge Base

PHP Response Header Examples

PHP can set headers for responses it generates. Send them before output, and remember that the server or CDN can still change what the visitor receives.

Headers before output

<?php
header('Content-Type: text/html; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');

// For a sensitive dynamic response:
header('Cache-Control: no-store');

This illustrative fragment must run before HTML, echoed text, or accidental whitespace output. PHP header calls normally replace matching PHP-managed headers, but do not control later server or CDN additions.

Cookie attributes

<?php
// Example attributes only; use your real session mechanism and token.
setcookie('__Host-session', 'EXAMPLE_VALUE', [
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

This requires an HTTPS deployment and a PHP version supporting the options array. It demonstrates cookie attributes, not a working authentication system. Never use the placeholder value as a session credential. Configure framework or PHP session cookies through the session mechanism actually in use.

Know the scope

A PHP header applies to the PHP response, not automatically to static files, server-generated redirects, or hosting error pages. Sensitive responses need a matching cache policy even if a cookie is present. CSP nonces require application integration, not a static pasted header.

Check the final response

Inspect the browser's response headers after all hosting layers. If PHP reports that headers were already sent, find the earlier output rather than hiding the warning. Check the cookie reference and duplicate header guide.

Sources

Copyright ©2026 MILAN INNOVATIONS LLC. All rights reserved.