Sling Academy
Home/PHP/How to Set Response Headers in PHP

How to Set Response Headers in PHP

Last updated: January 12, 2024

Introduction

One critical aspect of back-end development involves managing HTTP response headers. These headers control the way browsers and other clients handle the data they receive from a server. In PHP, setting response headers is a common task that can influence caching, content types, character sets, and handling of various other HTTP functions. In this tutorial, we will delve deep into how to set and manipulate HTTP response headers using PHP.

Understanding HTTP Headers

HTTP headers are part of the HTTP request and response messages. They are used to pass additional information between clients and servers. Response headers typically contain metadata like content length, content type, information about the server, instructions for caching, etc.

In PHP, the header() function is used to send raw HTTP headers to the client. The proper use of this function can refine your application’s functionality and make it more secure and efficient.

Setting Up the Environment

Before you begin, ensure that your server supports PHP and it’s currently running. If you’re using a local development environment like XAMPP or WampServer, make sure the services are started. In this tutorial, we won’t require any special libraries beyond the PHP core.

Syntax of the header() Function

header(string $header, bool $replace = true, int $response_code = 0)

The function accepts three parameters:

  • $header: The header string.
  • $replace: Whether to replace a previous similar header or add a second header of the same type. The default is true, meaning it will replace it.
  • $response_code: Forces the HTTP response code to the specified value.

How to Set Content Type and Character Set

Defining the content type is essential to inform the client about the type of content returned. PHP defaults to ‘text/html’, but it’s good practice to define it explicitly, especially when returning different formats:

header('Content-Type: text/html; charset=utf-8');

If you’re returning a JSON response, set the header as follows:

header('Content-Type: application/json');

Controlling Cache with Headers

Cache control headers determine whether or how a local cache stores the response.

To prevent caching, you can use:

header('Cache-Control: no-cache, no-store, must-revalidate');

If you want the browser to cache the response for a specific duration, use the ‘max-age’ directive with the number of seconds:

header('Cache-Control: max-age=3600');

Handling Redirects

Redirecting users is a common need, and PHP’s header() function can be used to send a location header:

header('Location: https://www.example.com');

Remember to exit the script after a redirect to stop the execution of the rest of the script:

exit;

Setting Custom Headers

Besides standard headers, you can define custom headers for additional control or information passing:

header('X-My-Custom-Header: 12345');

Managing Cookies

Cookies are also set using the header() function. The Set-Cookie header looks like this:

header('Set-Cookie: user=JohnDoe; expires=' . date('D, d M Y H:i:s', time() + 3600) . ' GMT');

Sending File Downloads

To initiate a file download, use the Content-Disposition header:

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');

Implementing file download triggers the ‘Save As’ dialog in the browser, prompting the user to save the file.

Adding Response Codes

The optional third parameter of the header() function can be used to send an HTTP status code:

header('HTTP/1.1 404 Not Found');

Good Practices

  • Always call the header() function before sending any output. Headers cannot be modified once output has begun.
  • Use header_remove() to remove headers.
  • Test your headers with tools like Postman or curl.
  • Be aware of PHP’s output buffering. If you have output buffering turned on, you can manipulate headers even after output has begun. However, it is not a recommended practice.

Conclusion

Working with HTTP headers in PHP gives you a lot of control over how your application’s output is handled on the client side. By learning how to use the header() function, you unlock a new level of detail in managing responses. While this guide covers several common scenarios, further exploration of HTTP specifications and the PHP manual will reveal even more about the power of header manipulation.

Happy Coding!

Next Article: How to extract User-Agent in PHP

Previous Article: How to Redirect to Another Page in PHP

Series: Building Dynamic Web Pages with PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array