The PHP header () function uses detailed (301, 404 error settings) _php instance

Source: Internet
Author: User
Tags http request learn php session id response code
If you are just beginning to learn PHP, there may be many functions to study, today we will learn how to use the PHP Header (), more instructions, please refer to the PHP Chinese manual, the following is about the Header function detailed use instructions

Header Implementation 404 Unable to find page

Copy Code code as follows:

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

For the ErrorDocument 404/404.php function in Apache configuration, the Nginx configuration

Copy Code code as follows:

Error_page 404/404.php;


Change into
Copy Code code as follows:

Error_page 404 =/404.php;


PHP Heager

Copy Code code as follows:

<?php
Header ("http/1.1 moved Permanently");
Header ("Location: $url");
?>



no matter how many headers the page has, 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 ' Fire net;
Header (' location:http://www.g.cn ');
Header (' location:http://www.baidu.com ');

This will jump to Google.
The following is a detailed instructions for using the header function
First, the role:
~~~~~~~~~
PHP is just the HTTP protocol to the HTML document headers to the browser, tell the browser how to deal with the page, as to the content of the transfer need to familiarize yourself with the HTTP protocol, and PHP has nothing to do
The traditional header must contain one of the following three kinds of headers and can only appear once.

Location:xxxx:yyyy/zzzz
Content-type:xxxx/yyyy
status:nnn xxxxxx

Second, first to understand how the HTTP protocol works
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The HTTP protocol is based on the request/response paradigm. After a client establishes a connection to the server, it sends a request to the server in the form of a Uniform Resource Identifier, protocol version number, followed by MIME information including the request modifier, client information, and possible content. When the server receives a request, it responds with a response that is formatted as a status line that includes the protocol version number of the information, a successful or erroneous 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 provision of HTTP services, the client refers to the browser you use or download tools and so on. When communicating, the client issues a request connection, the server establishes the connection, then the client sends an HTTP request (request), and the server returns the response information (Respond), which completes an HTTP operation.

Third, the HTTP protocol status code means
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1xx Retention
2XX indicates that the request was successfully received
3xx requesting customers to further refine requests for completion
4XX Customer Error
5XX Server Error


Iv. Operation Example:
~~~~~~~~~~~~~
<1> redirect function, this most common

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

<2> force users to get the most up-to-date information each time they visit this page, instead of using a client-side cache.

Code

<?php
Tells the browser when this page expires (in Greenwich Mean Time), as long as the date is already past.
Header ("Expires:mon, June June 1970 05:00:00 GMT");
Tell the browser that the last update date for this page (in GMT) is the same day, the purpose is to force the browser to get the latest information
Header ("last-modified:"). Gmdate ("D, D M Y h:i:s"). "GMT");
Tells the client that the browser does not use the cache
Header ("Cache-control:no-cache, must-revalidate");
Parameter (compatible with previous server), i.e. compatible 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");
File name in File Save dialog box by default
Header ("content-disposition:attachment; Filename= $filename ");
?>

<3> output status value to browser, mainly for access rights control

<?php
Header (' http/1.1 401 Unauthorized ');
Header (' status:401 unauthorized ');
?>

For example, to limit a user's inability to access the page, you can set the status to 404, as shown below, so that the browser appears as if 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 kinds of headers and can only appear once. CONTENT-TYPE:XXXX/YYYY location:xxxx:yyyy/zzzz status:nnn xxxxxx can appear more than two times in the new multi-header specification (Multipart MIME).
Usage examples
Example one: This example redirects the browser to the official website of PHP.

Header ("location:http://www.jb51.net/"); Exit

Example two: You can use the following headers when you want the user to get the latest information, not the Proxy or cache data.

Header ("Expires:mon, June June 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 three: Let the user's browser appear to be unable to find the file information.

Header ("status:404 not Found");

Example four: Allow users to download files.

Header ("Content-type:application/x-gzip");
Header ("content-disposition:attachment; filename= filename ");
Header ("Content-description:php3 generated Data");

Header--Sends an original HTTP header description

void header (String 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 specification.
Optional parameter replace indicates whether to replace the previous similar header or to add a header of the same type. The default is replace, but if you set it to FALSE, you can force multiple homogeneous headers to be sent. For example:

<?php
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 a new addition to the PHP 4.3.0).
There are two kinds of special header calls. The first is that the header begins with the string "http/" (not case important) and can be used to determine the HTTP status code to send. For example, if you have Apache configured with PHP to handle error-handling requests that cannot find a file (using the errordocument Directive), you need to make sure that the script produces the 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 without the actual header () call being the first. Unless the HTTP headers have been sent out, you can overwrite the original by invoking the header () function with the new status line at any time.

HTTP status Detection (HTTP Header):

The second special case is the "Location:" header. It does not just send the header back to the browser, it 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 is not executed after redirection.
Exit
?>

Note: The http/1.1 standard requires a URI of an absolute address as the Location: parameter, but there are some clients that support relative URIs. You can usually use the $_server[' http_host ', $_server[' php_self ', and the DirName () function 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 the session.use_trans_sid,session ID is enabled, it will not be delivered with Location header information. SID constants must be passed by hand.
  
PHP scripts typically produce dynamic content that must not be cached by the browser or proxy server. Many proxy servers and browsers can be prevented from caching by the following methods:

<?php
Header ("Cache-control:no-cache, must-revalidate"); http/1.1
Header ("Expires:mon, June June 1997 05:00:00 GMT"); The time of the past
?>

Note: You may find that the Web page is not buffered even if you do not output all of the above code. The user has many options to set to change the browser's default caching behavior. By sending this header, you should be able to overwrite any settings that can cause the script page 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 the header () must be invoked before any actual output, whether from a normal HTML tag, a blank line, or PHP. One common error is when you read code through include (), require (), or some other file access class function, some spaces or blank lines are sent out before the header () is invoked. This error is also common in a separate php/html file.

<?php
/* This will produce an error because the header is being tuned ()
* I've already exported something before * *
Header (' location:http://www.example.com/');
?>

Note: Since PHP 4, some output buffering functions can be used to solve this problem. The tradeoff is that all output to the browser is slowed to the server until the next command sends them. You can use Ob_start () and Ob_end_flush () in your code to do this, either by modifying the output_buffering configuration options in php.ini, or by modifying the server configuration file.

Header () Two common usage:

To set the page encoding:
Header (' content-type:text/html;charset=gb2312 ');
To adjust the page:
Header (' location:http://www.baidu.com ');

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.