In PHP, the header() function sends raw HTTP headers. One common use is to perform page redirection by setting the Location header.
header('Location: https://www.example.com');
exit;
In this example, the header() function sets the Location header to the target URL, then exit is called to stop script execution and ensure redirection.
1. No output (including spaces or line breaks) should be sent before calling header().
2. After redirection, the script does not stop automatically; use exit or die to terminate execution.
3. The Location header can point to URLs inside or outside the current domain.
The header() function can also set HTTP response headers such as Content-Type and Cache-Control.
header('Content-Type: application/json');
echo json_encode(['name' => 'John', 'age' => 30]);
This example sets the response content type to JSON and outputs corresponding JSON data.
1. Response headers must be set before any output.
2. Content-Type can be set to values like 'application/json', 'text/html', etc., depending on your needs.
Use header() to set HTTP status codes to inform clients about the result of their request.
header('HTTP/1.1 404 Not Found');
echo 'Sorry, the page you requested could not be found.';
This example sets the status code to 404 and outputs a not found message.
1. Choose appropriate status codes and reason phrases carefully.
2. If not set, the default status code is 200 OK.
The header() function can also set cache-related HTTP headers to improve page load speed.
header('Cache-Control: max-age=3600');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
echo 'This page is cached for 1 hour.';
This example sets the cache validity to 1 hour.
1. Configure cache directives and parameters based on actual needs.
2. Combining Cache-Control and Expires headers more effectively controls caching.
Use header() to set Content-Disposition and enable file download functionality.
header('Content-Disposition: attachment; filename="example.txt"');
echo 'This is the content of example.txt file.';
This prompts the browser to open a download dialog, saving the file as example.txt.
1. Make sure Content-Disposition and filename are set correctly.
2. For large files, consider outputting content in chunks to avoid high memory usage.
This article summarizes various common uses of PHP’s header() function, including page redirection, response header setting, status code configuration, cache control, and file downloading. Mastering these techniques enables developers to handle HTTP requests and responses more flexibly, enhancing website functionality and user experience.