
HTTP headers are vital to HTTP requests and responses. They provide various details about the request and the response to the server and the client (respectively). In PHP, it is possible to set HTTP headers that will be sent in the server’s response. This allows you to customize various aspects of the HTTP response.
Useful things to change in the HTTP response include cache control, expirations and server details. You can even redirect the user to another page using HTTP headers. PHP supports both the sending of HTTP 1.0 and 1.1 headers. For sending headers, we use the header() function in PHP.
header() accepts three parameters, with only the first being required. The first parameter is the header string, which is where you set the HTTP header you want to set in the response. This is in the format of Type: value. The second parameter is a boolean replace option. If you’re setting multiple headers of the same type, setting this to true (the default) will replace the one before it, and setting it to false will force the setting of multiples headers of the same type. The third parameter allows you to force the HTTP response status code.
A list of the different types of response headers you can send is available here. Additionally, you can use a different format of the first parameter to send a response status code. This format is like this: HTTP/1.1 404 Not Found. The format is the HTTP version, followed by the status code, followed by the status code’s name.
It’s important to note that a header() tag must come before any output (from PHP or just HTML placed before the PHP block), otherwise a fatal error will be issued and page execution stopped. Also note that when sending a Location header, nothing should be executed or outputted after it. To ensure this, it is good measure to place an exit; directly after a Location header.
Now, let’s look at some examples:
[code='php']header('HTTP/1.1 200 OK');[/code]
Send the status code 200 (this is the default for a page that exists).
[code='php']header('Location: http://www.google.com/');[/code]
Redirect the client to google.com. By default PHP will send this as a 302 Temporary Redirect. Also note that HTTP/1.1 requires absolute URLs for this header.
[code='php']header('HTTP/1.1 301 Moved Permanently');
header('Location: http://www.example.com/');[/code]
Redirect the client to example.com and send a 301 Moved Permanently status code.




