PHPheader () function usage details (301, 404 and other error settings) _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Tags response code
Use the PHPheader () function in detail (error settings such as 301 and 404 ). If you have just started learning PHP, there may be many functions that need to be studied. today we will learn how to use PHPHeader (). for more instructions, please refer to the PHP Chinese manual, 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

The code is as follows:


Header ("HTTP/1.1 404 Not Found ");


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

The code is as follows:


Error_page 404/404 .php;



Change

The code is as follows:


Error_page 404 =/404.php;



Php hemanager 301

The code is as follows:


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

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

// 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.

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.

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:

  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.

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.

  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:

  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:

  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.

  
   /* 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 ');

For more instructions on using expose Header (), refer to the PHP Chinese manual ,...

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.