PHP header() Function

Learn via video courses
Topics Covered

The header() function in PHP is an essential tool for manipulating HTTP response headers, enabling developers to control various aspects of web communication. It facilitates precise management of content types, caching policies, and redirections. Importantly, it allows for the setting or modification of headers before delivering output, ensuring seamless server-client interactions. This functionality is crucial for enhancing application performance, managing response statuses such as 404 or 200, and extending script capabilities with raw HTTP headers, thereby making it a cornerstone in PHP web development. Now, let's discuss the syntax of PHP header.

Syntax

The syntax of the header() function in PHP is as follows:

Explanation The header() function in PHP is used to send an HTTP header to the browser. Here is an explanation of the parameters:

  • $header (required): Specifies the header to be sent. It should be a valid HTTP header string, such as "Content-Type: text/html" or "Location: https://example.com".
  • $replace (optional): Indicates whether the specified header should replace a previous header with the same name. By default, it is set to true, allowing replacement of the header. If set to false, the new header will be appended to any existing headers with the same name.
  • $http_response_code (optional): Specifies the HTTP response code to be sent. It can be used to send specific HTTP status codes such as 200, 404, or 500. If not provided, the server will use the default response code of 200 (OK). Run the above code in your editor for a better and clear explanation.

Basic Working Example

Explanation In the above example

  • The header('Content-Type: text/plain') line sets the Content-Type header to specify that the response should be treated as plain text. This is useful when you want to send text-based content to the browser.
  • The header('X-Custom-Header: Hello, world!') line sets a custom header named X-Custom-Header with the value "Hello, world!". This demonstrates how you can add custom headers to your PHP responses.
  • The header('Refresh: 5; URL=https://example.com') line sends a Refresh header that redirects the user to the specified URL (https://example.com) after 5 seconds. This is useful for performing redirects or refreshing a page after a certain time. Run the above code in your editor for a better and clear explanation.

Parameter Values

The header() function in PHP allows you to set various parameter values to control the behavior and characteristics of the HTTP response. Here are some commonly used parameter values:

Content-Type:

  • Example: header('Content-Type: text/html')
  • Specifies the MIME type of the content being sent. Common values include text/html for HTML content, application/json for JSON content, image/jpeg for JPEG images, etc. Location
  • Example: header('Location: https://example.com')
  • Used for redirecting the user to a different URL. The value should be a valid URL to which the user will be redirected. Cache-Control:
  • Example: header('Cache-Control: no-cache, no-store')
  • Controls caching behavior in the browser. Values like no-cache, no-store, private, public, etc., can be used to specify cache control directives. Expires:
  • Example: header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT')
  • Specifies the expiration date and time for the content being sent. It helps in caching and instructs the browser when to consider the content as expired. Content-Disposition:
  • Example: header('Content-Disposition: attachment; filename="file.pdf"')
  • Used for specifying the behavior of the content being sent. For example, an attachment suggests that the content should be treated as a file attachment, and a filename specifies the name of the file. HTTP Response Code:
  • Example: header('HTTP/1.1 404 Not Found')
  • Sets the HTTP response code for the current request. Common codes include 200 OK, 404 Not Found, 500 Internal Server Error, etc.

Return Value

The header function in PHP is used to send HTTP headers to the client's web browser as part of the server's response. It does not return a value. When the header function is called, it immediately sends the specified header to the browser. Its purpose is to modify the HTTP response sent by the server, allowing developers to customize various aspects such as redirecting users to different pages, setting cookies, enabling caching, and specifying the content type of the response. The function does not provide any direct feedback or result to the PHP script itself. It is important to note that headers must be sent before any content is outputted, or it may result in a "Headers already sent" warning or error. The header function is a powerful tool for managing HTTP response headers and enhancing the functionality and user experience of PHP applications.

Example:

Run the above code in your editor for a better and clear explanation.

PHP Changelog

  • PHP 4.0.2: The header() function was introduced in PHP 4.0.2.
  • PHP 4.3.0: Before PHP 4.3.0, the header() function had a limitation that it could only be called before any actual output was sent to the browser. If the output was already sent, calling header() would result in a warning. Starting from PHP 4.3.0, this limitation was relaxed, and it became possible to use header() after output had been sent, as long as no output had been flushed to the browser yet.
  • PHP 5.1.0: In PHP 5.1.0, the header() function gained an optional third parameter $http_response_code. This parameter allows specifying the HTTP response code directly when setting headers. Before this version, the response code had to be set using a separate function, such as http_response_code().
  • PHP 7.0.0: In PHP 7.0.0, the header() function was made case-insensitive, meaning that the header names are no longer required to be in a specific case. This change was made to align with HTTP specification requirements.

More Examples

How to Download Files Using a Header in PHP

Explanation In the above example:

  • Set the $file variable to the path of the file you want to download.
  • Check if the file exists using file_exists(). If it does, proceed with the download. If not, display an error message.
  • Set the necessary headers:
  • Content-Type: application/octet-stream indicates that the response contains binary data.
  • Content-Disposition: attachment; filename="[filename]" specifies that the file should be treated as an attachment with the provided filename.
  • Content-Length: [filesize] provides the size of the file in bytes. Run the above code in your editor for a better and clear explanation.

How to Prevent Page Caching Using Headers in PHP?

Explanation In the example above, the following cache control headers are set:

  • Cache-Control: no-store - Specifies that the response should not be stored in any cache, including the browser cache or intermediate caches.
  • Cache-Control: no-cache - Indicates that the response can be cached, but it must be revalidated with the server on each request. The cached copy cannot be used without first checking with the server.
  • Cache-Control: must-revalidate - Instructs the browser and intermediate caches to revalidate the response with the server before using a cached copy.
  • Cache-Control: max-age=0 - Sets the maximum age of the response to 0 seconds, effectively telling the browser to always revalidate the response with the server. Run the above code in your editor for a better and clear explanation.

Conclusion

  • The header() function in PHP allows developers to control various aspects of HTTP headers, such as content type, caching, redirection, and more.
  • Headers facilitate communication between the server and the client's web browser, enabling the exchange of information and instructions.
  • Headers offer customization options, allowing developers to optimize content delivery, enhance security, handle redirects, and control browser caching.
  • Headers should be set before any output is sent to the browser, ensuring they are sent in the initial response from the server. Headers cannot be modified once output has been sent.