How to Remove HTTP Headers in PHP with header_remove

This article explains how to use PHP’s built-in header_remove() function to delete previously defined HTTP headers before they are sent to the client. You will learn the syntax of the function, how to remove specific headers, and how to clear all headers at once with practical code examples.

Understanding header_remove()

The header_remove() function in PHP is used to remove HTTP headers that were previously set using the header() function. This is particularly useful when you need to override or cancel headers set by core scripts, plugins, or frameworks earlier in the execution cycle.

Syntax

header_remove(?string $name = null): void

How to Remove a Specific HTTP Header

To remove a specific header, pass its name as a string argument to the header_remove() function. The header name is case-insensitive.

Example:

<?php
// Set a custom header
header("X-Custom-Header: MyValue");

// Set another custom header
header("X-Delete-Me: TemporaryValue");

// Remove only the "X-Delete-Me" header
header_remove("X-Delete-Me");
?>

In this example, only X-Custom-Header will be sent to the browser; X-Delete-Me is deleted before the response is dispatched.


How to Remove All HTTP Headers

If you want to clear all headers set by PHP in the current script execution, call header_remove() without passing any arguments.

Example:

<?php
// Set multiple headers
header("X-First-Header: One");
header("X-Second-Header: Two");

// Clear all previously set headers
header_remove();
?>

Calling the function without parameters ensures a clean slate, removing every header defined by your PHP scripts up to that point.


Important Considerations

  1. Headers Already Sent: Like the header() function, header_remove() will not work if the HTTP headers have already been sent to the client. Headers are sent as soon as any output (like HTML, spaces, or echo statements) is generated. You can use headers_sent() to verify if headers can still be modified:

    if (!headers_sent()) {
        header_remove("X-Foo");
    }
  2. Web Server Headers: header_remove() can only remove headers set by PHP. It cannot remove headers automatically added by your web server (such as Apache or Nginx) or PHP’s session management (like Set-Cookie headers generated by session_start(), unless you configure session settings accordingly).