PHP header() function usage details (301, 404 and other error settings)_PHP tutorial

WBOY
Release: 2016-07-21 15:11:51
Original
720 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 are detailed instructions for the header function.

Header implements 404 page not found

Copy code The code is as follows:

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

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

Copy code The code is as follows:
error_page 404 /404.php;


changed to

Copy code The code is as follows:
error_page 404 = /404.php;



php heager 301

Copy code The code is as follows:
header("HTTP/1.1 301 Moved Permanently");
header ("Location:$url");
?>




No matter how many headers the page has, it will execute 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 'Bangkezhijia;
header('Location:http: //www.g.cn');
header('Location:http://www.baidu.com');

This will jump to google
The following is about the header function Detailed instructions for use
1. Function:
~~~~~~~~~
PHP just sends the header of the HTML document to the browser using the HTTP protocol, 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. 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. The meaning of HTTP protocol status code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1XX >

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

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

<2> Force users to get the latest every time they visit this page data instead of using the cache that exists on the client side.

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 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 the browser will display 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 header specification (Multipart MIME).
Usage Example
Example 1: This example redirects the browser to the official website of PHP.

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

Example 2: Want users to get the latest data every time, not Proxy Or the data in the 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 file not found message.

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 newly added 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 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):

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 browser*/
 /* Ensure that after redirection, follow up The code will not be executed*/
Exit;
?>

Note: The HTTP/1.1 standard requires an absolute address URI as the parameter of Location:, but some clients support relative URI. 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 and must be passed manually using the SID constant. Usually some dynamic content is generated, which must not be cached by the browser or proxy server. Many proxy servers and browsers can disable caching by the following method:

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

Note: You may find that even without outputting all the code above, the page is not buffered. There are many options that users can set to change the default caching behavior of the browser. By sending the above header, it should be possible. Override any settings that would cause script pages to be cached.

Additionally, when using sessions, 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 to save files via include(), require() or some other. When the class function reads the code, some spaces or empty lines are sent before calling header(). This error is also common in a separate 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 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/326841.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!