In PHP, the header()
function is used to send raw HTTP headers to the client. These headers are typically used to provide instructions to the browser about how the content should be handled or to convey additional information about the response. The header()
function must be called before any actual output is sent to the browser, including HTML tags and whitespace.
Here is the basic syntax of the header()
function:
phpheader(string $header, bool $replace = true, int $http_response_code = null);
- header: The header string to be sent to the client.
- replace (optional): A boolean parameter that indicates whether to replace any existing headers of the same type. By default, it is set to
true
, which means that if a header with the same name already exists, it will be replaced. If set tofalse
, the new header will be appended to the existing headers with the same name. - http_response_code (optional): The HTTP response code to send. This parameter allows you to specify the HTTP status code for the header. If not provided, the previous status code remains unchanged.
Here are a few examples of how the header()
function is commonly used:
- Setting a Location header for redirection:
phpheader("Location: http://www.example.com");
This example redirects the user to the specified URL by sending a "Location" header.
- Setting the content type to plain text:
phpheader("Content-Type: text/plain");
This sets the "Content-Type" header to indicate that the content being sent is plain text.
- Setting the HTTP response code:
phpheader("HTTP/1.1 404 Not Found");
This example sets the HTTP response code to 404, indicating that the requested resource was not found.
It's important to note that after calling header()
, no further output should be sent to the browser. If there is any output before calling header()
, it may result in an error.
Here's a simple example combining several headers to perform a redirect:
php<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.newlocation.com");
exit();
// Ensure that no further code is executed after the header
?>
In this example, the header()
function is used to send a 301 status code along with a "Location" header to redirect the user to a new location. The exit()
function is called immediately afterward to ensure that no additional code is executed.
No comments:
Post a Comment