PHP header() - Send HTTP Header
The header() function in PHP is a powerful tool used to send raw HTTP headers to the client before any actual output is sent. It enables developers to control various aspects of the HTTP response such as redirects, content types, caching policies, and more. Mastering this function is essential when working with network-related PHP features or managing how your web server communicates with browsers and APIs.
Prerequisites
- Basic understanding of PHP syntax and server-side scripting.
- Knowledge of HTTP protocol and headers.
- Web server environment to run PHP (Apache, Nginx, etc.)
- PHP installed (version 5.x or newer recommended).
Setup
To use the header() function, simply write PHP code in a file with a .php extension and run it in your server environment. Ensure no output (like echo or HTML) is sent before calling header(), or headers might fail to send.
Understanding header() Function
The syntax for header() is:
header(string $header, bool $replace = true, int $response_code = 0): void
$header: The HTTP header string to send.$replace: Optional. Whether to replace a previous similar header (default:true).$response_code: Optional. Forces HTTP response code to specified value.
Common Use Cases & Examples
1. Redirecting to another URL
<?php
// Redirect user to another page
header("Location: https://www.example.com/");
exit;
?>
Note: Always call exit; after redirect to stop script execution.
2. Changing Content-type
<?php
// Send JSON content type header
header("Content-Type: application/json");
echo json_encode(["status" => "success"]);
?>
3. Controlling Caching
<?php
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
?>
4. Forcing Download of a File
<?php
$file = 'example.pdf';
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
header("Content-Length: " . filesize($file));
readfile($file);
exit;
?>
Best Practices
- No Output Before Headers: Ensure no whitespace, echo, or HTML outputs before calling
header(). PHP sends headers as soon as output starts, locking the headers. - Use
exit;After Redirects: To prevent further code execution after a redirect header. - Specify Response Code When Necessary: Use the third parameter in
header()to set appropriate HTTP status codes, e.g., 404 or 301. - Sanitize Header Values: Avoid injecting user data directly into headers to prevent header injection attacks.
- Cache Control: Properly control caching headers to avoid stale content or security issues.
Common Mistakes to Avoid
- Calling
header()after any output (e.g., echo, HTML tags) results in the error: "Cannot modify header information - headers already sent". - Omitting
exit;after header redirects, which causes unintended script execution. - Incorrectly formatting headers (missing colon or invalid values).
- Using multiple
Locationheaders without proper replacement flags. - Ignoring HTTP status codes while sending headers, e.g., redirect without 301 or 302 response code.
Interview Questions
Junior Level
- Q: What does the PHP
header()function do?
A: It sends raw HTTP headers to the client before any output is sent. - Q: Can you use
header()after echoing output?
A: No, headers must be sent before any output, otherwise an error will occur. - Q: How do you redirect a user to a different URL using
header()?
A: Useheader("Location: URL");followed byexit;. - Q: What happens if you forget to use
exit;after a redirect header?
A: The rest of the script executes, which may cause unintended behavior. - Q: How do you specify the content type for an HTTP response?
A: Useheader("Content-Type: type");, e.g.,application/json.
Mid Level
- Q: What is the purpose of the
$replaceparameter inheader()?
A: It controls whether the new header should replace a previous one of the same name. Default istrue. - Q: How can you set a custom HTTP response code using
header()?
A: Use the third parameter:header("Header", true, 404);. - Q: Explain how to prevent caching using
header().
A: Send headers likeCache-Control: no-cache, no-store, must-revalidate,Pragma: no-cache, andExpires: 0. - Q: How would you force a file download using headers?
A: SendContent-Type: application/octet-stream,Content-Disposition: attachment, and specify file length, then output file content. - Q: What error do you encounter if you call
header()after output? How to fix it?
A: "Headers already sent" error; fix by ensuring no output (including whitespace) is sent before callingheader().
Senior Level
- Q: How does PHP handle multiple header calls with the same header name, and how can you control this behavior?
A: By default, headers with the same name are replaced. Using the$replace = falseargument allows multiple headers of the same name. - Q: What precautions should you take regarding header injection vulnerabilities when using
header()?
A: Sanitize inputs to ensure no CRLF characters are injected, preventing attackers from adding malicious headers. - Q: Describe how you would send a custom HTTP authentication challenge header using
header().
A: Send something likeheader('WWW-Authenticate: Basic realm="My Realm"');along with a 401 status code. - Q: How does the HTTP version affect headers sent by PHP through
header()?
A: PHP sends headers according to the server and PHP’s SAPI; you can influence response code but not directly protocol version throughheader(). - Q: Explain a scenario where forgetting to set
replaceargument to false would cause bugs.
A: When sending multiple headers of the same name (e.g., Set-Cookie), forgettingreplace=falsewill overwrite previous ones, leading to missing cookies.
FAQ
Q: Why does PHP sometimes show "Headers already sent" error?
A: This error occurs because output (even a whitespace/newline outside tags) has been sent before calling header(). Headers must be sent before any output.
Q: Can I send multiple headers of the same name?
Yes, by setting the second parameter $replace to false, e.g., header("Set-Cookie: name=value", false);
Q: How do I set a 404 Not Found status with header()?
Use: header("HTTP/1.1 404 Not Found"); or header("", true, 404);
Q: Can I use header() to send custom headers?
Yes, you can send any valid HTTP header, including custom headers like X-Custom-Header: value.
Q: Does header() affect output buffering?
If output buffering is enabled, headers can be sent as long as the buffer hasn’t flushed the output yet.
Conclusion
The PHP header() function is an essential feature for managing HTTP response headers, enabling developers to control redirects, caching, content types, and more. Following the best practices and understanding common pitfalls ensures you use it effectively without runtime errors. With this tutorial, you're now equipped to harness the power of HTTP headers in your PHP applications to improve user experience, security, and performance.