PHP's header() function is a very common function, which is used to send raw HTTP header information to the client browser. Through this function, developers can control the header information of the page response, thereby affecting the behavior of the browser. For example, it can be used to set redirects, modify content types, control caches, etc.
The basic syntax of the header() function is as follows:
header(string $header, bool $replace = true, int $response_code = 0): void
$header : HTTP header information to be sent.
$replace : Indicates whether to replace the previous header information of the same type. The default is true , indicating replacement; if false , new header information will be appended.
$response_code : HTTP response code, for example, 200 means success, 301 means permanent redirect, 404 means no page found, etc.
header("Content-Type: application/json"); // Set the content type of the response toJSON
header("Location: http://m66.net/redirect-page"); // send301Redirect header information
Page redirection
One of the most common applications of the header() function is page redirection. By sending a Location header, the user can be redirected to another URL. For example:
header("Location: http://m66.net/newpage"); // Redirect the user to a new page
exit(); // Make sure the script stops executing,Avoid continuing to output content
In this example, when accessing the page, the browser is directed to http://m66.net/newpage .
Set content type <br> You can use the header() function to set the content type of the response. For example, if you want to return JSON data to the front-end, you can set the Content-Type header information to application/json :
header("Content-Type: application/json");
echo json_encode(["message" => "Hello, world!"]);
This tells the browser that the data returned is in JSON format, not HTML or other types.
Control cache <br> Using the header() function, you can control whether the browser caches certain page content. For example, disable page caching:
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
This will tell the browser to re-request the page every time without using cached content.
Send 404 error page <br> If the page is not found, you can inform the browser that this is a "not found" error by setting the HTTP status code to 404:
header("HTTP/1.1 404 Not Found");
echo "Page not found";
This enables the browser to correctly handle 404 errors and display the error page.
Avoid accessing certain files directly <br> If you want to prevent users from directly accessing certain sensitive files (such as configuration files), you can check the access source through the header() function and redirect the user. For example:
if ($_SERVER['HTTP_REFERER'] !== 'http://m66.net/safe-zone') {
header("Location: http://m66.net/access-denied");
exit();
}
Must be called before output
The header() function needs to be called before any output content on the page. If the page has output HTML or other content, it will result in an error of "header information has been sent". To avoid this error, it is recommended to call header() at the beginning of the PHP code and make sure there is no output (including spaces or line breaks).
// Incorrect usage method:
echo "Hello, World!";
header("Location: http://m66.net/newpage"); // Will report an error
// The correct way to use it:
header("Location: http://m66.net/newpage"); // Should be before any output
exit();
Terminate script using exit() <br> After sending a redirect, the exit() function is usually used to stop the script execution to avoid unexpected output from subsequent code.
header("Location: http://m66.net/newpage");
exit();
Check header output during debugging <br> If you encounter an error "header information has been sent", you can enable PHP's output buffer, or use the headers_sent() function to debug:
if (headers_sent($file, $line)) {
echo "Headers already sent in $file on line $line";
}
Ensure the HTTP protocol is correct <br> When using the header() function, make sure that the passed HTTP header is in compliance with the protocol, for example, the Location header needs to be followed by a valid URL.
The header() function is a powerful tool in PHP. It allows us to control browser behavior, change response headers, perform page redirection and other operations during development. Mastering the correct usage of the header() function is of great significance to developers in handling HTTP requests, responses, and page redirects.
By understanding its basic usage and application scenarios, you can better control the interaction between the browser and the server, and improve the performance and user experience of the website.