What is the purpose of the header function in PHP?
The header function in PHP is used to send HTTP header information. It can be used in PHP scripts to set response Content-Type, cache control, redirection, and other HTTP header information.
Specific functions include:
- Use the header function to set the Content-Type in order to inform the browser how to parse the data being returned from the server, such as setting it to “text/html” to indicate that an HTML document is being returned.
- Set cache control: you can set cache control headers using the header function, for example setting “Cache-Control” to “no-cache” to prevent browsers from caching page content.
- Implementing redirection: you can use the header function to set the “Location” header information, achieving URL redirection and automatically redirecting the browser to the specified page.
- You can set the status code using the header function, for example setting it to “HTTP/1.1 404 Not Found” indicates that the page was not found.
- Send other custom HTTP headers: Use the header function to send additional custom HTTP headers, such as setting “X-Powered-By” to indicate the technology used by the server.
It is important to note that the header function must be called before any output is produced, otherwise it will result in an error.