header

header(string $header, bool $replace = true, int $response_code = 0): void

Sends a raw HTTP response header: with setcookie and http_response_code it completes the web response control trio; must be called before any output, and is a silent no-op under CLI where headers_list() is always empty.

C C23

C23
#include <stdio.h>

int main(void) {
    // No header() exists - a CGI program literally prints the header lines,
    // then the blank line that separates headers from the body
    printf("Content-Type: application/json\n");
    printf("X-Demo: 1\n");
    printf("\n"); // end of headers
    printf("body: json\n");
    return 0;
}
Output
Content-Type: application/json
X-Demo: 1

body: json

C++ C++26

C++26
#include <iostream>

int main() {
    // Same as C: headers are hand-written lines, a blank line, then the body
    std::cout << "Content-Type: application/json\n"
              << "X-Demo: 1\n"
              << "\n" // end of headers
              << "body: json\n";
}
Output
Content-Type: application/json
X-Demo: 1

body: json

C# v11.0.100

v11.0.100
// Typed headers on HttpResponseMessage (what ASP.NET Core hands your handler)
using System.Net;
using System.Net.Http;

HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK);
res.Content = new StringContent("body: json");
res.Headers.TryAddWithoutValidation("X-Demo", "1");
Console.WriteLine("status: " + (int)res.StatusCode);
Console.WriteLine("x-demo: " + string.Join("", res.Headers.GetValues("X-Demo")));
Output
status: 200
x-demo: 1

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	// w.Header().Set + WriteHeader is the header API; httptest records instead of sending
	rec := httptest.NewRecorder()
	var w http.ResponseWriter = rec
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Demo", "1")
	w.WriteHeader(http.StatusOK)
	fmt.Println("status:", rec.Code)
	fmt.Println("x-demo:", rec.Header().Get("X-Demo"))
}
Output
status: 200
x-demo: 1

Java v27.0.1

v27.0.1
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;

public class Main {
    public static void main(String[] args) throws Exception {
        // JDK built-in HttpServer: getResponseHeaders() is the header map
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/demo", exchange -> {
            exchange.getResponseHeaders().set("Content-Type", "application/json");
            exchange.getResponseHeaders().set("X-Demo", "1");
            byte[] body = "body: json".getBytes();
            exchange.sendResponseHeaders(200, body.length);
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        server.start();
        // request it back with the JDK client and read the headers
        java.net.http.HttpClient client = java.net.http.HttpClient.newHttpClient();
        java.net.http.HttpRequest req = java.net.http.HttpRequest.newBuilder()
            .uri(java.net.URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/demo"))
            .build();
        java.net.http.HttpResponse<String> res = client.send(req, java.net.http.HttpResponse.BodyHandlers.ofString());
        System.out.println("status: " + res.statusCode());
        System.out.println("x-demo: " + res.headers().firstValue("X-Demo").orElse(""));
        server.stop(0);
    }
}
Output
status: 200
x-demo: 1

JavaScript v26.13.1

v26.13.1
// Node: res.setHeader()/writeHead() on the ServerResponse object
const http = require("node:http");
const server = http.createServer((req, res) => {
    res.setHeader("Content-Type", "application/json");
    res.setHeader("X-Demo", "1");
    res.writeHead(200);
    res.end("body: json");
});
server.listen(0, "127.0.0.1", () => {
    http.get(`http://127.0.0.1:${server.address().port}/demo`, (res) => {
        console.log("status:", res.statusCode);
        console.log("x-demo:", res.headers["x-demo"]);
        res.resume();
        res.on("end", () => server.close());
    });
});
Output
status: 200
x-demo: 1

PHP v8.6.0

v8.6.0
// header() only works under a Web SAPI; in CLI it is a silent no-op
// and headers_list() is always empty here
header("Content-Type: application/json");
header("X-Demo: 1");
$list = headers_list();
echo "sent: no-op in CLI\n";
echo "headers listed: ", count($list), "\n";
Output
sent: no-op in CLI
headers listed: 0

Python v3.15.2

v3.15.2
# http.server: send_response + send_header build the block; end_headers closes it
import http.server
import threading
import urllib.request


class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("X-Demo", "1")
        self.end_headers()
        self.wfile.write(b"body: json")

    def log_message(self, *args):
        pass  # keep stdout deterministic


server = http.server.HTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=server.serve_forever, daemon=True).start()
res = urllib.request.urlopen(f"http://127.0.0.1:{server.server_port}/demo")
print("status:", res.status)
print("x-demo:", res.headers["X-Demo"])
server.shutdown()
Output
status: 200
x-demo: 1

Rust v1.99.1

v1.99.1
fn main() {
    // No HTTP server in std; a CGI-style program prints the header block by hand
    print!("Content-Type: application/json\nX-Demo: 1\n\nbody: json\n");
}
Output
Content-Type: application/json
X-Demo: 1

body: json

TypeScript v26.13.1

v26.13.1
// Node: res.setHeader()/writeHead() on the ServerResponse object
import * as http from "node:http";
const server = http.createServer((req, res) => {
    res.setHeader("Content-Type", "application/json");
    res.setHeader("X-Demo", "1");
    res.writeHead(200);
    res.end("body: json");
});
server.listen(0, "127.0.0.1", () => {
    http.get(`http://127.0.0.1:${server.address().port}/demo`, (res) => {
        console.log("status:", res.statusCode);
        console.log("x-demo:", res.headers["x-demo"]);
        res.resume();
        res.on("end", () => server.close());
    });
});
Output
status: 200
x-demo: 1

Language differences

C/C++/Rust: no abstraction - headers are printf'd lines; the CGI blank-line separation is plain to see.

C#: in ASP.NET Core headers are the typed Response.Headers collection; HttpResponseMessage is the client-side counterpart.

Go: w.Header().Set must happen before WriteHeader/Write - later changes are ignored (classic pitfall); httptest.NewRecorder self-tests without a port.

Java: in a container the counterpart is HttpServletResponse.setHeader; the JDK's built-in com.sun.net.httpserver demos it directly.

JavaScript: Node's res.setHeader plus writeHead(status); frameworks (Express' res.set) just wrap it.

PHP: must be called before ANY output (else headers already sent); the Location: special case implies a 302; header_remove() retracts, headers_sent() detects, and everything stays silent under CLI.

Python: BaseHTTPRequestHandler assembles headers manually; production uses a framework (Flask/Django response objects).

TypeScript: same as JavaScript.

Extra: the special header("HTTP/1.1 404 Not Found") form is better replaced by http_response_code(); together with setcookie and http_response_code it forms the response-control trio.