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:
- $string: Required, specifies the original HTTP headers to be sent.
- $replace: Optional, specifies whether to replace previously sent headers of the same type. Default is true, indicating replacement.
- $http_response_code: Optional, sets the HTTP response code.
Example of usage:
- Specify the Content-Type
header("Content-Type: application/json");
- Redirect to a specified website.
header("Location: https://example.com");
- Set the HTTP response code.
header("HTTP/1.1 404 Not Found");
Please be mindful of the following:
- The header function must be called before any actual output, including any HTML tags, spaces, and line breaks.
- If there is any output before the header function, such as echo or print, the header function will fail.
- 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