What is the use of header() function in PHP?

The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output. For example, you can’t print any HTML element before using this function.

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:

  1. Setting HTTP Response Codes: You can use header() to set the HTTP response code, such as 404 for “Not Found” or 200 for “OK”.
  2. Redirecting Users: header() can be used to redirect users to another page by setting the “Location” header.
  3. Setting Content Type: You can use header() to specify the content type of the response, such as text/html, application/json, etc.
  4. Preventing Caching: Headers can be used to prevent caching of pages, ensuring that the most up-to-date content is always served.
  5. 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.