PHP header() is an inbuilt function that can redirect to any URL. The PHP header() function sends the HTTP header to the client or browser in raw form. Remember that the header() must be called before any actual output is sent, either by standard HTML tags, blank lines in the file, or from PHP. In PHP 4 version and later, you can use output buffering to solve this problem.
PHP header() Function
The HTTP functions are those functions that modify information sent to a client or browser by a Web server before any other output has been sent. Before HTML, XML, JSON or other output has been sent to the browser or client, and the raw data is sent with the request (especially HTTP Request) made by the server as header information.
HTTP header provides the required data about an object sent in the message body more precisely about the request and response.
#Syntax of header() Function
header( $header, $replace = TRUE, $http_response_code )
- $header: The $header parameter holds the header string. There are two types of header calls. The first header starts with the string “HTTP/,” which is used to figure out the HTTP status code to send. The second case of the header is the “Location:”. It is a mandatory parameter.
- $replace: The $replace is an optional parameter. It denotes the header should replace previous or add the second header. The default value is True (will replace). If $replace value is False, then it forces multiple headers of the same type.
- $http_response_code: The $http_response_code is an optional parameter. It forces an HTTP response code to the specified value (PHP 4.3 and higher).
See the following example.
<?php // Redirect the browser header("Location: https://appdividend.com");
#Prevent page caching in PHP
We can prevent page caching by using the header() function.
<?php // PHP program to describes header function header("Expires: Sun, 19 February 1994 06:02:34 GMT"); header("Cache-Control: no-cache"); header("Pragma: no-cache");
#Save PDF File
If we want functionality in which lets user be prompted to save a generated PDF file. Then the Content-Disposition header is used to supply the recommended filename and force the browser to display the save dialog box.
See the following code.
<?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='app.pdf'"); // The PDF source is in original.pdf readfile("data.pdf");
#Other Applications
- If we want to change the page location.
- If we want to set timezone.
- If we want the caching control.
- If we want to initiate force download.
- If we want to send HTTP Status.
Finally, PHP header() Function Example | header() Method In PHP Tutorial is over.