Home > Article > Backend Development > Analysis of the role of header function in php
In our previous article, we introduced you to the header header definition. So many people will ask if they have introduced it to customers before when they see the title. Does the client send raw HTTP headers? is it really like this? Today we will show you what the header function in php does.
Let’s take a look at the definition in the official document first
(PHP 4, PHP 5, PHP 7)
header — Send native HTTP header
1 void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
Parameters:
string
There are two special heads. The first one starting with "HTTP/" (case is not significant) will be used to calculate the HTTP status code to be sent. For example, if you use a PHP script on the Apache server to handle requests for non-existent files (using the ErrorDocument directive), you will hope that the script responds with the correct status code.
1 <?php 2 header("HTTP/1.0 404 Not Found"); 3 ?>
The second special case is the "Location:" header information. It not only sends the message to the browser, but also returns a REDIRECT (302) status code to the browser, unless the status code has been set to 201 or ## in advance. #3xx.
1 <?php 2 header("Location: http://www.example.com/"); /* Redirect browser */ 3 4 /* Make sure that code below does not get executed when we redirect. */ 5 exit; 6 ?>
replace<span style="font-family: Microsoft YaHei"></span>
Optional parameters replace Indicates whether to replace the previous header of the same type with the following header. Replaced by default. If you pass FALSE
, you can force the same header information to coexist. For example:
1 <?php 2 header('WWW-Authenticate: Negotiate'); 3 header('WWW-Authenticate: NTLM', false); 4 ?>
http_response_code
## Forces the value of the HTTP response. Note that this parameter is only valid when the messagestring (string) is not empty.
The common uses of the header function are as follows:
1. Redirectheader('Location: http://www.example.com/');
header('Content-type: application/pdf');
header('Content-type: application/pdf');
//指定内容为附件,指定下载显示的名字
header('Content-Disposition: attachment; filename="downloaded.pdf"');
//打开文件,并输出
readfile('original.pdf')
4. Allow users to obtain the latest information and data instead of caching
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // 设置临界时间
Detailed examples
##Summary: After reading this article, I believe you all know the functions of the header function in php. I hope it will be helpful to your work!
Related recommendations:Detailed explanation of header definition in php
The above is the detailed content of Analysis of the role of header function in php. For more information, please follow other related articles on the PHP Chinese website!