How to Send Custom HTTP Headers in PHP

Sending custom HTTP headers in PHP is a fundamental technique for passing metadata, managing API authentication, and controlling browser behavior. This guide provides a straightforward explanation of how to send custom headers both in a server’s response to a client and within client-side requests made to external APIs using PHP.

Sending Custom Headers in a Response

To send a custom header from your server back to the client (such as a browser or an API consumer), use PHP’s built-in header() function.

Custom headers should ideally begin with a standardized prefix or simply use clear, hyphenated naming conventions (e.g., X-My-Custom-Header or App-Version).

<?php
// Sending a custom response header
header("X-Custom-Header-Name: CustomHeaderValue");
header("App-Environment: Production");

// Output your content after headers are sent
echo json_encode(["status" => "success"]);
?>

Important Rule for Responses

You must call the header() function before any actual output (HTML, spaces, or echo statements) is sent to the browser. If output has already started, PHP will trigger a “headers already sent” warning and the header will not be delivered.


Sending Custom Headers in an Outgoing Request

If your PHP script needs to consume an external API and send custom headers (like Authorization or X-API-Key) along with the request, you can use either cURL or Stream Contexts.

cURL is the most robust and widely used tool for making HTTP requests in PHP. You can pass custom headers as an array of strings using the CURLOPT_HTTPHEADER option.

<?php
$url = "https://api.example.com/data";

// Initialize cURL session
$ch = curl_init($url);

// Define your custom headers
$headers = [
    "Authorization: Bearer YOUR_ACCESS_TOKEN",
    "X-Client-Version: 1.2.0",
    "Content-Type: application/json"
];

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute the request
$response = curl_exec($ch);

// Close connection
curl_close($ch);

echo $response;
?>

Method 2: Using file_get_contents with Stream Context

If cURL is not available on your server, you can send custom headers using file_get_contents by creating a custom stream context.

<?php
$url = "https://api.example.com/data";

// Define headers as a single string separated by carriage returns (\r\n)
$options = [
    "http" => [
        "method" => "GET",
        "header" => "Authorization: Bearer YOUR_ACCESS_TOKEN\r\n" .
                    "X-Client-Version: 1.2.0\r\n"
    ]
];

// Create the stream context
$context = stream_context_create($options);

// Send the request
$response = file_get_contents($url, false, $context);

echo $response;
?>