Home Backend Development PHP Tutorial Detailed explanation of the reasons why header location page jump fails

Detailed explanation of the reasons why header location page jump fails

May 18, 2018 am 10:47 AM
header location fail Page jump

http header information
Header information has many functions, the most important ones are the following:
1. Jump
When the browser receives the header After Location: xxxx in the information, it will automatically jump to the URL address pointed to by xxxx. This is a bit similar to writing a jump with js. But this jump is only known by the browser, and users cannot see it regardless of whether there is anything in the content.
Example: header("Location: http://www.php.cn/");
2. Specify the content of the web page
The same XML file, if the header information If you specify: Content-type: application/xml, the browser will parse it according to the XML file format. However, if the header information is: Content-type: text/xml, the browser will parse it as stored text. (Browsers do not parse files according to extensions)
Example: header('Content-type: application/pdf');
3. Attachment
I don’t know if you have noticed it , sometimes when downloading something from some websites, after clicking the download link, the browser opens the attachment as a web page, and the contents displayed are all garbled characters. This problem is also related to the header information. Sometimes the browser determines whether to open or save based on Content-type, so sometimes it will make a wrong judgment (mainly because the website designer forgets to write Content-type). In fact, there is another way to specify that the content is an attachment and needs to be saved. This is: Content-Disposition: attachment; filename="xxxxx"
Example: header('Content-Disposition: attachment; filename="downloaded.pdf "');
//Open the file and output
readfile('original.pdf');
HTTP protocol status code
1×× Reserved
2××"Indicates that the request was successful Receiving
3×× The customer needs to further refine the request to complete the request
4×× Customer error
5×× Server error

Syntax:

header(string,replace,http_response_code)
Copy after login

Parameter
string: required. Specifies the header string to be sent.
replace: optional. Indicates whether this header replaces the previous header, or adds a second header. Default is true (replacement). false (allow multiple headers of the same type).
http_response_code: Optional. Forces the HTTP response code to the specified value. (Available for PHP 4 and above)
Example 1:
Redirect web page

   <?php 
      header("Location: http://www.php.cn/");
      exit;
   ?>
Copy after login

Example 2:
Force users to get the latest information every time they visit this page, and Instead of using the cache that exists on the client side.

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

Example 3:
Output status value to the browser, mainly used for access control

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

Example 4:
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(&#39;HTTP/1.1    404    Not Found&#39;);  
       header("status:    404    Not Found"); //这种写法错误
   ?>
Copy after login

Example 5:
The location of the hidden file
html tag < A href='http://hostname/*.mp3'> can achieve ordinary file download. If you want to keep the file confidential and you cannot tell others the file link, you can use the header function to download the file.

header("Content-type: audio/mpeg");
header("Content-Disposition: attachment; filename=filenale");
header("Content-Description: PHP3 Generated Data");
Copy after login

Example 6:
Input content before the header function
Generally speaking, html content cannot be output before the header function. Similarly, there are setcookie() and session functions. These functions need to be in the output stream. Add message header information. If there are statements such as echo before header() is executed, when header() is encountered later, a "Warning: Cannot modify header information - headers already sent by ...." error will be reported. That is to say, there cannot be any text, blank lines, carriage returns, etc. in front of these functions, and it is best to add the exit() function after the header() function. For example, in the following incorrect writing, there is a blank line between the two php code sections:

<?php
//some code here
?>
//这里应该是一个空行
<?php
    header("http/1.1 403 Forbidden");
    exit();
?>
Copy after login

原因:
PHP脚本开始执行 时,它可以同时发送http消息头部(标题)信息和主体信息. http消息头部(来自 header() 或SetCookie() 函数)并不会立即发送,相反,它被保存到一个列表中. 这样就可以允许你修改标题信息,包括缺省的标题(例如Content-Type 标题).但是,一旦脚本发送了任何非标题的输出(例如,使用 HTML 或 print()调用),那么PHP就必须先发送完所有的Header,然后终止 HTTPheader.而后继续发送主体数据.从这时开始,任何添加或修改Header信息的试图都是不允许的,并会发送上述的错误消息之一。
解决办法:
修改php.ini打开缓存(output_buffering),将output_buffering=0修改成output_buffering=4096
或者在程序中使用缓存函数ob_start(),ob_end_flush() 等。原理是:output_buffering被启用时,在脚本发送输出时,PHP并不发送HTTPheader。相反,它将此输出通过管道(pipe)输入到动态增加的缓存中(只能在PHP4.0中使用,它具有中央化的输出机制)。你仍然可以修改/添加header,或者设置cookie,因为 header实际上并没有发送。当全部脚本终止时,PHP将自动发送HTTP header到浏览器,然后再发送输出缓冲中的内容。

The above is the detailed content of Detailed explanation of the reasons why header location page jump fails. For more information, please follow other related articles on the PHP Chinese website!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of PHP page jump function: page jump skills of header, location, redirect and other functions Detailed explanation of PHP page jump function: page jump skills of header, location, redirect and other functions Nov 18, 2023 pm 05:08 PM

Detailed explanation of PHP page jump functions: Page jump techniques for header, location, redirect and other functions, which require specific code examples. Introduction: When developing a Web website or application, jumping between pages is an essential function. PHP provides a variety of ways to implement page jumps, including header functions, location functions, and jump functions provided by some third-party libraries, such as redirect. This article will introduce in detail how to use these functions

How to solve problems encountered in Win11 23H2 update? How to solve problems encountered in Win11 23H2 update? Dec 25, 2023 pm 12:18 PM

Users usually upgrade the computer system version to fix some problems. If the user fails to update to the latest version of 23H2 using win11 system, there are three methods to solve your problem. What to do if Win11 update 23H2 fails. Method 1: Bypass TPM1, click "File Explorer - View", and check the "Hidden Items" option in the drop-down menu. 2. Go to and delete "C:\$WINDOWS.~BT\Sources\Panther-Appraiser_Data.ini". 3. Then re-create a folder with the same name in this location, and then click to cancel the "Hide Items" option. 4. Re-update the system and finally click on “Wind

Why can't localstorage successfully save data? Why can't localstorage successfully save data? Jan 03, 2024 pm 01:41 PM

Why does storing data to localstorage always fail? Need specific code examples In front-end development, we often need to store data on the browser side to improve user experience and facilitate subsequent data access. Localstorage is a technology provided by HTML5 for client-side data storage. It provides a simple way to store data and maintain data persistence after the page is refreshed or closed. However, when we use localstorage for data storage, sometimes

What does linux header mean? What does linux header mean? Jul 18, 2023 pm 03:34 PM

The Linux header refers to the beginning of a file or data stream, which is used to contain metadata about the content. By correctly writing and using Header files, developers can better utilize system resources and improve code readability and Maintainability.

Analysis of location configuration examples in Nginx server Analysis of location configuration examples in Nginx server May 24, 2023 pm 02:05 PM

First, let me briefly introduce the types of location and matching rules, using the example of nginxwiki as an example: location=/{#matchesthequery/only.[configurationa]}location/{#matchesanyquery,sinceallqueriesbeginwith/,butregular#expressionsandanylongerconventionalblockswillbe#matchedfirst.[ configurationb]}location^~/im

How to solve the problem of pip update failure? How to solve the problem of pip update failure? Jan 27, 2024 am 08:32 AM

What should I do if pip update fails? Recently, while developing in Python, I encountered some problems with pip update failure. When developing, we often need to use pip to install, upgrade and remove Python third-party libraries. The failure of pip update will seriously affect our development work. This article will discuss some common pip update failures and provide solutions, hoping to help developers who encounter similar problems. First, when we execute pipinstall-

Use uniapp to achieve page jump animation effect Use uniapp to achieve page jump animation effect Nov 21, 2023 pm 02:15 PM

Title: Using uniapp to achieve page jump animation effect In recent years, the user interface design of mobile applications has become one of the important factors in attracting users. Page jump animation effects play an important role in improving user experience and visualization effects. This article will introduce how to use uniapp to achieve page jump animation effects, and provide specific code examples. uniapp is a cross-platform application development framework developed based on Vue.js. It can compile and generate applications for multiple platforms such as mini programs, H5, and App through a set of codes.

PHPStudy installation problem revealed: What should I do if PHP 5.5 version fails? PHPStudy installation problem revealed: What should I do if PHP 5.5 version fails? Feb 29, 2024 am 11:54 AM

PHPStudy is a development environment tool that integrates PHP, Apache, and MySQL, providing developers with a convenient way to build a local server environment. However, you may encounter some problems during the installation process, one of which is the failure to install the PHP5.5 version. This article will discuss the reasons and solutions for PHPStudy's failure to install PHP5.5 version, and provide specific code examples to help readers solve this problem. PHPStudy installs PHP5.5 version

See all articles