In PHP, the header()
function is used to send raw HTTP headers to the client. These headers are used to provide additional information to the client’s browser or other applications communicating with the PHP script.
Here are some common uses of the header()
function:
- Setting HTTP Response Codes: You can use
header()
to set the HTTP response code, such as 404 for “Not Found” or 200 for “OK”.
- Redirecting Users:
header()
can be used to redirect users to another page by setting the “Location” header.
- Setting Content Type: You can use
header()
to specify the content type of the response, such as text/html, application/json, etc.
- Preventing Caching: Headers can be used to prevent caching of pages, ensuring that the most up-to-date content is always served.
- Setting Cookies:
header()
can be used to set cookies in the user’s browser.
However, it’s essential to note that header()
must be called before any actual output is sent to the browser. Otherwise, you may encounter errors like “Headers already sent” in PHP.