Sobes.tech
Junior

What syntax is used for headers in PHP?

sobes.tech AI

Answer from AI

In PHP, the header() function is used to send HTTP headers.

header("Content-type: text/html"); // Sending Content-Type header
header("Location: http://example.com/"); // Redirect to another URL
header("HTTP/1.0 404 Not Found"); // Sending a 404 status code

Important points:

  • The header() function must be called before any output is sent to the browser (e.g., HTML code, whitespace outside <?php ... ?> tags).
  • You can send multiple headers by calling the header() function multiple times.
  • To replace an existing header, use the third parameter replace, which defaults to true. If set to false, headers with the same name will be added, not replaced.

Example with header replacement:

header("X-Custom-Header: Value1");
header("X-Custom-Header: Value2", false); // Adds a second header with the same name
header("X-Custom-Header: Value3"); // Replaces all previous X-Custom-Header headers

You can also use the headers_sent() function to check if headers have already been sent, and headers_list() to get a list of headers that have been sent.

What syntax is used for headers in PHP? — PHP - sobes.tech