PHP header() Function: Everything You Need to Know
As a PHP developer, you may need to manipulate HTTP headers in your web application. The header() function is a powerful tool that allows you to set HTTP headers in your PHP scripts. In this guide, we will cover the syntax, key parameters, and common use cases of the header() function.
What is the header() Function?
The header() function is a PHP built-in function that allows you to send raw HTTP headers to the client.
How to Use the header() Function
Using the header() function is straightforward. Here is the syntax of the function:
The PHP syntax of header() Function
header(string $header, bool $replace = true, int $response_code = 0);The function takes three parameters:
string: The header string to be sent.replace: A boolean indicating whether to replace previous headers with the same name. Defaults totrue.code: The HTTP response code to send. Defaults to200(or0in modern PHP).
Important: The header() function must be called before any output is sent to the browser (including HTML, whitespace, or echo statements). If output has already been sent, PHP will throw a "Headers already sent" warning. You can check if headers have been sent using headers_sent(), or use output buffering (ob_start()) to delay output.
Here is an example of how to use the header() function to set an HTTP header:
How to Use the header() Function?
<?php
header("Content-Type: application/json");In this example, we set an HTTP header called Content-Type with the value application/json. This header will be sent to the client when the script is executed.
You can also use the replace and code parameters to send redirects or custom status codes:
<?php
// Send a 301 Moved Permanently redirect
header("Location: https://example.com", true, 301);Conclusion
The header() function is a powerful tool for manipulating HTTP headers in your PHP web application. By understanding its syntax, parameters, and the requirement to call it before output, you can effectively manage redirects, content types, and status codes in your scripts.
Practice
What does the PHP header function do?