search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the use of PHP header() function

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/"); 
?> 

(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"); 
?>

(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'); 
?>

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"); 
?>

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); 
?>

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

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

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

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

注: 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); 
?> 

  注: 即使启用了 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"); // 过去的时间 
 ?>

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

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

  注: 自 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函数使用要点



Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools