Home > Backend Development > PHP Tutorial > Detailed description of PHP header() function (301, 404 and other error settings)_PHP tutorial

Detailed description of PHP header() function (301, 404 and other error settings)_PHP tutorial

WBOY
Release: 2016-07-21 14:58:23
Original
1516 people have browsed it

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 is about Detailed instructions for using header function

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

header('Location:http://www.bkjia.com');
header('Location:http://www.g.cn');
header('Location:http: //www.baidu.com');

This will jump to Baidu

header('Location:http://www.bkjia.com');echo 'Bangkezhijia;
header('Location:http://www.g.cn');
header('Location:http://www.baidu.com');

This will jump to Google
The following are detailed instructions for using the header function
1. Function:
~~~~~~~~~
PHP only converts HTML using the HTTP protocol The header of the document is sent to the browser, telling the browser how to process this page. As for the transmitted content, you need to be familiar with the HTTP protocol, which has nothing to do with 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

2. First, let’s understand 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. The 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), thereby completing an HTTP operation.

HTTP status detection (HTTP Header): http://www.bkjia.com/tools/http_header.php

3. The meaning of HTTP protocol status code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1×× Reserved
2×× Indicates that the request was successfully received
3×× To complete the request, the customer needs to further refine the request
4×× Customer error
5×× Server error

4. Operation examples:
~~~~~~~~~~~~~
<1> Redirect function, this is the most common

Header("Location: http://www.bkjia.com/");
?>

<2> Force users to access this every time Get the latest data when the page is running, rather than using the client's cache.

Code
//Tell the browser the expiration time of this page (expressed in Greenwich Mean Time), as long as it is a date that has already passed.
header("Expires: Mon, 26 Jul 1970 05:00:00 GMT");
//Tell the browser the last updated date of this page (expressed in Greenwich Mean Time), which is the current day. The purpose is 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 cache
header("Cache-Control: no-cache, must-revalidate");
//Parameters (compatible with previous servers), 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");
//Accepted range units
header("Accept-Ranges: bytes");
//The default file name in the file save dialog box
header("Content-Disposition: attachment; filename=$filename");
?>

<3> Output the status value to the browser, mainly used for access control

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

header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
?>

Note: Traditional headers 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 Example
Example 1: This example redirects the browser to the official website of PHP.

Header("Location: http://www.bkjia.com/"); exit;

Example 2: If you want the user to get 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: Let the user's browser display a message that the file cannot be found.

header("Status: 404 Not Found");

Example 4: Allow users to download files.

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

header -- Send a raw HTTP header description

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

The header() function is used to send a raw HTTP header. See the HTTP/1.1 specification for more information on HTTP headers.
 The optional parameter replace indicates whether to replace the previous similar header or add a header of the same type. The default is replacement, but setting it to FALSE can force multiple headers of the same type to be sent. For example:

  header('WWW-Authenticate: Negotiate');
 header('WWW-Authenticate: NTLM', false);
 ?>

The second optional parameter http_response_code forces the HTTP response code to the specified value (this parameter is new in PHP 4.3.0).
There are two special header calls. The first is a header that begins with the string "HTTP/" (case does not matter), which can be used to determine the HTTP status code to be sent. For example, if you configure Apache to use PHP to handle error-handling requests for file not found (using the ErrorDocument directive), you need to ensure that the script generates the correct status code.

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

Note: The HTTP status code header line is always the first one sent to the client, regardless of whether the actual header() call is the first one. Unless HTTP headers have already been sent, they can be overwritten at any time by calling the header() function with a new status line.

 HTTP status detection (HTTP Header): http://www.bkjia.com/tools/http_header.php

The second special case is the "Location:" header. It doesn't just send this header back to the browser, it also returns a REDIRECT (302) status code to the browser, unless a 3xx status code has been issued previously.

  header("Location: http://www.example.com/"); /* Redirect the browser*/
 /* Make sure that after redirection, the subsequent code will not Executed*/
exit;
?>

Note: The HTTP/1.1 standard requires an absolute address URI as the parameter of Location:, but some clients support relative URIs. You can usually use the $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() functions to generate absolute URIs from relative URIs yourself:

  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 passed along with the Location header information. Must be passed manually as SID constant.
 
  PHP scripts usually generate some dynamic content, which must not be cached by browsers or proxy servers. Many proxy servers and browsers can disable caching by:

GMT"); // Past time
 ?>

Note: You may find that even if you do not output all the above codes, the web page is not buffered. There are many options that users can set to change the browser's default caching behavior. By sending the above headers, it should be possible to override any settings that could cause script pages to be cached.

 

In addition, when session is used, the session_cache_limiter() function and the session.cache_limiter option can be used to automatically generate the correct cache-related headers.

Remember that header() must be called before any actual output, whether from regular HTML markup, blank lines or PHP. A common mistake is that when reading code through include(), require() or some other file access function, some spaces or empty lines are sent before calling header(). This error is also common in a single PHP/HTML file.

 
  /* This will generate an error because something has been output before calling header()
 */
 header('Location: http://www.example.com/');
 ?>

Note: Since PHP 4, this problem can be solved through some output buffering functions. The cost is that all output to the browser is cached on the server until a command is issued to send it. You can use ob_start() and ob_end_flush() in the code to achieve this function, or by modifying the output_buffering configuration option in php.ini, or by modifying the server configuration file.

Attached are two common uses of header():

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363871.htmlTechArticleIf you have just started learning PHP, there may be many functions to study. Today we will learn about PHP Header() How to use, for more instructions, please refer to the PHP Chinese manual,...
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