PHP header () function Usage Details (301, 404, and other error settings)

Source: Internet
Author: User

If you have just started learning PHP, there may be many functions that need to be studied. Today we will learn how to use PHP Header (). For more instructions, please refer to the PHP Chinese manual. The following describes how to use the header function.

The page cannot be found because the header is 404

Copy codeThe Code is as follows:
Header ("HTTP/1.1 404 Not Found ");

For the ErrorDocument 404/404. php function in apache configuration

Copy codeThe Code is as follows:
Error_page 404/404 .php;


Change
Copy codeThe Code is as follows:
Error_page 404 =/404.php;


Php hemanager 301

Copy codeThe Code is as follows:
<? Php
Header ("HTTP/1.1 301 Moved Permanently ");
Header ("Location: $ url ");
?>



No matter how many headers there are on the page, it executes the last one, but it is conditional. For example:

Header ('location: http://www.jb51.net ');
Header ('location: http://www.g.cn ');
Header ('location: http://www.baidu.com ');

This will jump to Baidu

Header ('location: http://www.jb51.net '); echo 'House of friends;
Header ('location: http://www.g.cn ');
Header ('location: http://www.baidu.com ');

This will jump to google
The following describes how to use the header function.
I. role:
~~~~~~~~~
PHP only sends the HTML document header to the browser using the HTTP protocol to tell the browser how to handle the page. As for the transmitted content, you need to familiarize yourself with the HTTP protocol, which is irrelevant to PHP.
The traditional header must contain one of the following three headers and can only appear once.

Location: xxxx: yyyy/zzzz
Content-Type: xxxx/yyyy
Status: nnn xxxxxx

Ii. First, let's take a look at how HTTP works.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP is based on the request/response paradigm. After a client establishes a connection with the server, it sends a request to the server in the format of Uniform Resource Identifier and Protocol version number, the MIME information is followed by the request modifier, client information, and possible content. After receiving the request, the server sends a response in the format of a Protocol version number containing the information, a successful or wrong code in the status line, MIME information is followed by server information, entity information, and possible content.
It consists of four processes. In the HTTP protocol, the server refers to the part that provides the HTTP service, and the client refers to the browser or download tool you use. During communication, the client sends a Request to connect and the server establishes a connection. Then, the client sends an HTTP Request, and the server returns the response information (Respond) to complete an HTTP operation.

Iii. Meaning of HTTP status code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1 × Reserved
2×× indicates that the request is successfully received.
3×× further refine the request to complete the request
4×× customer Error
5×× Server Error


4. Operation example:
~~~~~~~~~~~~~
<1> Redirection function, which is the most common

<? Php
Header ("Location: http://www.jb51.net /");
?>

<2> force users to obtain the latest information each time they access this page, instead of using the cache that exists on the client.

Code

<? Php
// Tell the browser the expiration time of this page (expressed by Greenwich Mean Time), as long as it is a date that has passed.
Header ("Expires: Mon, 26 Jul 1970 05:00:00 GMT ");
// Tell the browser the last update date (expressed by Greenwich Mean Time) of this page, that is, the day, to force the browser to obtain the latest information
Header ("Last-Modified:". gmdate ("D, d m y h: I: s"). "GMT ");
// Tell the client browser not to use the cache
Header ("Cache-Control: no-cache, must-revalidate ");
// Parameter (compatible with the previous server), that is, compatible with HTTP1.0 Protocol
Header ("Pragma: no-cache ");
// Output MIME type
Header ("Content-type: application/file ");
// File length
Header ("Content-Length: 227685 ");
// Unit of acceptable range
Header ("Accept-Ranges: bytes ");
// The file name in the "Save saved files" dialog box
Header ("Content-Disposition: attachment; filename = $ filename ");
?>

<3> outputs the status value to the browser, which is mainly used for access permission control.

<? Php
Header ('HTTP/1.1 401 unauthorized ');
Header ('status: 401 unauthorized ');
?>

For example, to restrict a user from accessing this page, you can set the status to 404, as shown below, so that the browser shows 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 MIME Type.
Example
Example 1: In this example, the browser is redirected to the official PHP website.

Header ("Location: http://www.jb51.net/"); exit;

Example 2: to obtain the latest data every time, instead of the data in the Proxy or cache, you can use the following Header

Header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT ");
Header ("Last-Modified :". gmdate ("D, d m y h: I: s "). "GMT"); header ("Cache-Control: no-cache, must-revalidate ");
Header ("Pragma: no-cache ");

Example 3: make the user's browser unable to find the file information.

Header ("Status: 404 Not Found ");

Example 4: allow users to download files.

Header ("Content-type: application/x-gzip ");
Header ("Content-Disposition: attachment; filename = file name ");
Header ("Content-Description: PHP3 Generated Data ");

Header -- send an original HTTP header description

Void header (string [, bool replace [, int http_response_code])

The header () function is used to send an original HTTP header. For more information about HTTP headers, see the HTTP/1.1 Standard.
The optional parameter replace indicates whether to replace the previous similar header or add a same type of header. It is replaced by default, but if it is set to FALSE, multiple similar headers can be forcibly sent. For example:

<? Php
Header ('www-Authenticate: negotiate ');
Header ('www-Authenticate: ntlm', false );
?>

The second optional parameter http_response_code sets the HTTP response code to a specified value (this parameter is newly added by PHP 4.3.0 ).
There are two special header calls. First, the header starts with the string "HTTP/" (Case Insensitive) and can be used to determine the HTTP status code to be sent. For example, if Apache is configured to use PHP to handle error handling requests that cannot find files (using the ErrorDocument command), make sure that the script generates a correct status code.

<? Php
Header ("HTTP/1.0 404 Not Found ")
?>

Note: The HTTP status code header line is always the first to be sent to the client, regardless of whether the actual header () call is the first. Unless the HTTP header has been sent out, you can use a new status line to call the header () function to overwrite the original one.

HTTP status detection (HTTP Header ):

The second special case is the "Location:" header. It not only sends this header back to the browser, but also returns a REDIRECT (302) status code to the browser, unless a 3xx status code has been issued before.

<? Php
Header ("Location: http://www.example.com/");/* redirect browser */
/* Ensure that subsequent code will not be executed after redirection */
Exit;
?>

Note: The HTTP/1.1 Standard requires an absolute url uri as the Location: parameter, but some clients support relative Uris. You can use the $ _ SERVER ['HTTP _ host'], $ _ SERVER ['php _ SELF '], and dirname () functions to generate an absolute URI from the relative URI:

<? Php
Header ("Location: http: // % 22. $ _ server ['HTTP _ host'/]
. Rtrim (dirname ($ _ SERVER ['php _ SELF ']),'/\ ')
. "/". $ Relative_url );
?>

Note: Even if session. use_trans_sid is enabled, the Session ID will not be transmitted along with the Location header. The SID constant must be passed manually.
  
PHP scripts usually generate some dynamic content, which must not be cached by browsers or proxies. Many proxy servers and browsers can be cached in the following way:

<? Php
Header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
Header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // past time
?>

Note: The webpage may not be buffered even if no code above is output. You can set many options to change the default cache behavior of your browser. By sending the above header, You can overwrite any settings that can cause the script page to be cached.
  
In addition, when session is used, the session_cache_limiter () function and session. cache_limiter option can be used to automatically generate correct cache-related headers.
  
Remember that header () must be called before any actual output, whether from common HTML tags, empty lines, or PHP. One common error is that when reading code through include (), require () or some other file access function, some spaces or blank lines call header () previously sent. This error is also common in a separate PHP/HTML file.

<Html>
<? Php
/* This will generate an error because the header ()
* Something has been output before */
Header ('location: http://www.example.com /');
?>

Note: from PHP 4, some output buffer functions can be used to solve this problem. The cost is to cache all the output to the browser on the server until the following command sends them. You can use ob_start () and ob_end_flush () in the code to implement this function, or modify php. the output_buffering configuration option in ini can also be implemented by modifying the server configuration file.

Appendix header:

// Set the page encoding:
Header ('content-Type: text/html; charset = gb2312 ');
// Adjust the page:
Header ('location: http://www.baidu.com ');

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.