Home > Backend Development > PHP Tutorial > Detailed explanation of the use of PHP header() function

Detailed explanation of the use of PHP header() function

WBOY
Release: 2016-07-25 09:11:46
Original
1035 people have browsed it

Please note: No matter how many headers the page has, it will execute the last one, but it is conditional, for example:

  1. header('Location:http://bbs.it-home.org');
  2. header('Location:http://www.g.cn');
  3. header('Location:http ://www.baidu.com');
Copy the code

This will jump to Baidu

  1. header('Location:http://bbs.it-home.org');
  2. header('Location:http://www.g.cn');
  3. header('Location:http: //www.baidu.com');
Copy the code

This will jump to google

Detailed instructions for using header function

1. Function PHP only sends the header of the HTML document to the browser using the HTTP protocol and tells the browser how to process the page. As for the transmitted content, you need to be familiar with the HTTP protocol and has nothing to do with PHP. Traditional headers must contain one of the following three headers and can only appear once. Location: xxxx:yyyy/zzzz Content-Type: xxxx/yyyy Status: nnn xxxxxx

2. How the HTTP protocol operates The HTTP protocol is based on the request/response paradigm. After a client establishes a connection with the server, it sends a request to the server. The format of the request is a uniform resource identifier, a protocol version number, followed by MIME information including request modifiers, client information and possible content. After receiving the request, the server gives corresponding response information. Its format is a status line including the protocol version number of the information, a success or error code, followed by MIME information including server information, entity information and possible content. It is divided into four processes. In the HTTP protocol, the server refers to the part that provides HTTP services, and the client refers to the browser or download tool you use, etc. During communication, the client sends a request for connection, and the server establishes the connection; then, the client sends an HTTP request (Request), and the server returns response information (Respond), thus completing an HTTP operation.

3. HTTP protocol status code 1×× reserved 2×× indicates that the request was successfully received 3×× In order to complete the request, the customer needs to further refine the request 4×× Customer error 5×× Server error

Four. Operation examples (1) Redirect function, this is the most common

<?php 
   Header("Location: http://www.php.net/"); 
?> 
Copy after login

(2). Force users to obtain the latest information every time they visit this page, instead of using the cache stored on the client.

<?php 
//告诉浏览器此页面的过期时间(用格林威治时间表示),只要是已经过去的日期即可。 
header("Expires: Mon, 26 Jul 1970 05:00:00 GMT"); 
//告诉浏览器此页面的最后更新日期(用格林威治时间表示)也就是当天,目的就是强迫浏览器获取最新资料 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); 
//告诉客户端浏览器不使用缓存 
header("Cache-Control: no-cache, must-revalidate"); 
//参数(与以前的服务器兼容),即兼容HTTP1.0协议 
header("Pragma: no-cache"); 
//输出MIME类型 
header("Content-type: application/file"); 
//文件长度 
header("Content-Length: 227685"); 
//接受的范围单位 
header("Accept-Ranges: bytes"); 
//缺省时文件保存对话框中的文件名称 
header("Content-Disposition: attachment; filename=$filename"); 
?>
Copy after login

(3), output the status value to the browser, mainly used for access permission control

<?php 
header('HTTP/1.1 401 Unauthorized'); 
header('status: 401 Unauthorized'); 
?>
Copy after login

For example, if you want to restrict a user from accessing this page, you can set the status to 404, as shown below, so that the browser will display that the page does not exist:

<?php 
header('HTTP/1.1 404 Not Found'); 
header("status: 404 Not Found"); 
?>
Copy after login

Note: The traditional header must contain one of the following three headers and can only appear once. Content-Type: xxxx/yyyy Location: xxxx:yyyy/zzzz Status: nnn xxxxxx can appear more than twice in the new multipart header specification (Multipart MIME). Usage examples Example 1: This example redirects the browser to PHP's official website.

  1. Header("Location: http://www.php.net/"); exit;
Copy code

Example 2: You want users to get the latest data every time, and If the data is not in Proxy or cache, you can use the following header

  1. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  2. header("Last-Modified: " . gmdate ("D, d M Y H:i:s") . "GMT"); header("Cache-Control: no-cache, must-revalidate");
  3. header("Pragma: no-cache");
Copy the code

Example 3: Let the user's browser display a message that the file cannot be found.

  1. header("Status: 404 Not Found");
Copy code

Example 4: Let users download files.

  1. header("Content-type: application/x-gzip");
  2. header("Content-Disposition: attachment; filename=filename");
  3. header("Content-Description: PHP3 Generated Data" );
Copy code

header -- 发送一个原始 HTTP 标头说明 void header ( string string [, bool replace [, int http_response_code]] )   header() 函数用来发送一个原始 HTTP 标头。有关 HTTP 标头的更多内容见 HTTP/1.1 规范。 可选参数 replace 指明是替换掉前一条类似的标头还是增加一条相同类型的标头。默认为替换,但如果将其设为 FALSE 则可以强制发送多个同类标头。例如:

<?php 
  header('WWW-Authenticate: Negotiate'); 
  header('WWW-Authenticate: NTLM', false); 
?>
Copy after login

第二个可选参数 http_response_code 强制将 HTTP 响应代码设为指定值(此参数是 PHP 4.3.0 新加的)。 有两种特殊的 header 调用。第一种是标头以字符串“HTTP/”(大小写不重要)开头的,可以用来确定要发送的 HTTP 状态码。例如,如果配置了 Apache 用 PHP 来处理找不到文件的错误处理请求(使用 ErrorDocument 指令),需要确保脚本产生了正确的状态码。

<?php 
 header("HTTP/1.0 404 Not Found") 
?>
Copy after login

  注: HTTP 状态码标头行总是第一个被发送到客户端,而并不管实际的 header() 调用是否是第一个。除非 HTTP 标头已经发送出去,任何时候都可以通过用新的状态行调用 header() 函数来覆盖原先的。    第二种特殊情况是以“Location:”标头。它不只是把这个标头发送回浏览器,它还将一个 REDIRECT(302)状态码返回给浏览器,除非之前已经发出了某个 3xx 状态码。

<?php 
  header("Location: http://www.example.com/"); /* 重定向浏览器 */ 
  /* 确保重定向后,后续代码不会被执行 */ 
  exit; 
?> 
Copy after login

注: HTTP/1.1 标准需要一个绝对地址的 URI 做为 Location: 的参数, 但有一些客户端支持相对 URI。通常可以使用 $_SERVER['HTTP_HOST']、$_SERVER['PHP_SELF'] 及 dirname() 函数来自己从相对 URI 产生出绝对 URI:

<?php 
  header("Location: http://%22.$_server['http_host'/] 
  . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') 
  ."/".$relative_url); 
?> 
Copy after login

  注: 即使启用了 session.use_trans_sid,Session ID 也不会随着 Location 头信息被传递。必须手工用 SID 常量来传递。      PHP 脚本通常会产生一些动态内容,这些内容必须不被浏览器或代理服务器缓存。很多代理服务器和浏览器都可以被下面的方法禁止缓存: 

<?php 
  header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 
  header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // 过去的时间 
 ?>
Copy after login

  注: 可能会发现即使不输出上面所有的代码,网页也没有被缓冲。用户有很多选项可以设置来改变浏览器的默认缓存行为。通过发送上述标头,应该可以覆盖任何可以导致脚本页面被缓存的设置。      另外,当使用了 session 时,利用 session_cache_limiter() 函数和 session.cache_limiter 选项可以用来自动产生正确的缓存相关标头。      要记住 header() 必须在任何实际输出之前调用,不论是来自普通的 HTML 标记,空行或者 PHP。有一个常见错误就是在通过 include(),require() 或一些其它的文件存取类函数读取代码时,有一些空格或者空行在调用 header() 之前被发送了出去。同样在一个单独的 PHP/HTML 文件中这个错误也很普遍

<?php 
  /* 这将产生一个错误,因为在调 header() 
  * 之前已经输出了东西 */ 
  header('Location: http://www.abc.com/'); 
?>
Copy after login

  注: 自 PHP 4 起,可以通过一些输出缓冲函数来解决这个问题。代价是把所有向浏览器的输出都缓存在服务器,直到下命令发送它们。可以在代码中使用 ob_start() 及 ob_end_flush() 来实现这样的功能,或者通过修改 php.ini 中的 output_buffering 配置选项来实现,也可以通过修改服务器配置文件来实现。

附header()两个常用用法:

  1. //设置页面编码:
  2. header('Content-Type:text/html;charset=gb2312');
  3. //调整页面:
  4. header('location:http://bbs.it-home.org');
复制代码

您可能感兴趣的文章: php header()函数的简单例子 php header函数实现文件下载的实例代码 php中header函数的用法举例详解 php header 使用详解 php header函数 文件下载时直接提示保存的代码 php header头信息应用举例 php 文件头部(header)信息详解 PHP中HEADER头消息详解 php header函数使用要点



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template