How is the header used in PHP?

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

Syntax: header(string $string, bool $replace = true, int $http_response_code = null)

Parameters:

  1. $string: Required, specifies the original HTTP headers to be sent.
  2. $replace: Optional, specifies whether to replace previously sent headers of the same type. Default is true, indicating replacement.
  3. $http_response_code: Optional, sets the HTTP response code.

Example of usage:

  1. Specify the Content-Type
header("Content-Type: application/json");
  1. Redirect to a specified website.
header("Location: https://example.com");
  1. Set the HTTP response code.
header("HTTP/1.1 404 Not Found");

Please be mindful of the following:

  1. The header function must be called before any actual output, including any HTML tags, spaces, and line breaks.
  2. If there is any output before the header function, such as echo or print, the header function will fail.
  3. If you need to send multiple headers, you can call the header function multiple times.

For more detailed information, please refer to the official PHP documentation at: https://www.php.net/manual/en/function.header.php

bannerAds