Explore the usage of headers in PHP _php tutorial

Source: Internet
Author: User
Tags setcookie
Header()is used to send raw HTTPHeaders. See the http/1.1 specification for more information on HTTPHeaders.

Example One:
Copy CodeThe code is as follows:
Header ("location:http://www.jb51.net";);
exit;//must add "exit" after each redirect to avoid an error and continue execution.
?>

Copy CodeThe code is as follows:
Header ("Refresh:2;url=http://www.jb51.net");
echo "Loading, please wait ...
Three seconds after automatic jump to Baidu ... ";
?>

--------------------------------------------------------------------------------
Example Two: Prohibit pages from being cached in IE
Enable the browser to get the latest information each time, not the Proxy or cache information:
Copy CodeThe code is as follows:
Header (' Expires:fri, 4 Dec 09:00:00 GMT ');
Header (' last-modified: '. Gmdate (' d, D M Y h:i:s '). ' GMT ');
Header (' Cache-control:no-store, No-cache, Must-revalidate ');
Header (' cache-control:post-check=0, pre-check=0 ', false);
Header (' Pragma:no-cache '); Compatible with http1.0 and HTTPS
?>

CacheControl = No-cache Pragma=no-cache Expires = 1
If the Web page on the server changes frequently, set expires to 1, which means that it expires immediately. If a webpage is updated daily 1 o'clock in the morning, you can set expires to 1 o'clock in the morning the next day. When the HTTP1.1 server specifies CacheControl = No-cache, the browser does not cache the page.
Legacy HTTP 1.0 Servers cannot use the Cache-control header. So for backwards compatibility with HTTP 1.0 servers, IE uses the Pragma:no-cache header to provide special support for HTTP. Internet Explorer does not cache this response if the client communicates with the server over a secure connection (https://) and the server returns a Pragma:no-cache header in the response.
Note: Pragma:no-cache prevents caching only when used in a secure connection, and if used in a non-secure page, is processed in the same way as expires:-1, the page is cached but is marked for immediate expiration.
HTTP-EQUIV META Tags:
You can use HTTP-EQUIV meta to mark the header of the specified HTTP message in an HTML page. Older versions of IE may not support HTML meta tags, so it is best to use the HTTP message header to disable caching.
--------------------------------------------------------------------------------
Example Three: Let the user's browser appear unable to find the file information.
A lot of information on the Internet so write: Php function header () can send a status header to the browser,
such as the header ("status:404 not Found"). However, the response returned by the browser is actually:
Copy CodeThe code is as follows:
http/1.x OK
Date:thu, 2006 07:49:11 GMT
server:apache/2.0.55 (WIN32) php/5.0.5
x-powered-by:php/5.0.5
status:404 not Found
content-length:0
Keep-alive:timeout=15, max=98
Connection:keep-alive
Content-type:text/html

Check some information, the correct wording is:
Header ("http/1.1 404 Not Found");
The first part is the version of the HTTP Protocol (http-version), the second part is the status code, and the third part is the reason phrase (reason-phrase).
--------------------------------------------------------------------------------
Example four: Let the user download the archive (the location of the hidden file)
HTML tags can be used to achieve normal file download. If in order to keep confidential files, you can not send the file link to others, you may use the header function for file download.
Copy CodeThe code is as follows:
Header ("Content-type:application/x-gzip");
Header ("content-disposition:attachment; Filename= file name/");
Header ("Content-description:php3 Generated Data");
?>

example four: input content before header function
In general, you cannot output HTML content before the header function, similar to the Setcookie () and session functions, which need to add message header information to the output stream. If there is an echo statement before the header () is executed, the "Warning:cannot Modify header Information-headers already sent by ..." error is reported when the header () is encountered later. This means that there cannot be any text, blank lines, carriage returns, etc. in front of these functions, and it is best to add the exit () function after the header () function. For example, in the following error notation, there is a blank line between the two PHP code snippets:
Copy CodeThe code is as follows:
Some code here
?>
This is supposed to be a blank line.
Header ("http/1.1 403 Forbidden");
Exit ();
?>

The reasons are:When the PHP script starts executing, it can send both the HTTP message header (header) information and the principal information. The HTTP message header (from the header () or the Setcookie () function) is not immediately sent, instead it is saved to a list. This allows you to modify the header information, including the default title (for example, the Content-type title). However, once the script sends any non-header output (for example, using HTML or print () calls), then PHP must first send all headers and then terminate HTTP header. Then continue to send the principal data. From this point on, any attempt to add or modify header information is not allowed, and one of the above error messages is sent.
Workaround:
Modify PHP.ini to open the cache (output_buffering), or use the cache function Ob_start (), Ob_end_flush (), etc. in the program. The principle is: When output_buffering is enabled, PHP does not send an HTTP header when the script sends the output. Instead, it imports this output through a pipeline (pipe) into a dynamically increasing cache (only used in PHP 4.0, which has a centralized output mechanism). You can still modify/add a header, or set a cookie because the header is not actually sent. When all the scripts are terminated, PHP automatically sends the HTTP header to the browser, and then sends the contents of the output buffer.
=================================================================
PHP Manual Instance Application
1: You can use the Heder command to force the browser to use fresh content (no cache).
You can also add a unique number to the URL so that it reads new content every time and avoids caching.
Example
Copy CodeThe code is as follows:
Print ""; The cache file is usually read
?>
Print ""; Added a unique number to make the browser request again
W//print "";
?>

2: Here is a good function to send the picture to the browser display.
Copy CodeThe code is as follows:
function Pe_img_by_path ($PE _imgpath = "")
{
if (file_exists ($PE _imgpath)) {
$PE _imgarray = pathinfo ($PE _imgpath);
$iconcontent = file_get_contents ($PE _imgpath);
Header ("content-type:image/". $PE _imgarray["extension"]);
Header (' Content-length: '. strlen ($iconcontent));
Echo $iconcontent;
Die (0);
}
return false;
}
?>

More examples:
Copy CodeThe code is as follows:
Ok
Header (' http/1.1 OK ');
Set a 404 Header:
Header (' http/1.1 404 Not Found ');
Set address to be permanently redirected
Header (' http/1.1 301 Moved permanently ');
Go to a new address
Header (' location:http://www.baidu.com ');
File Delay Steering:
Header (' refresh:10; url=http://www.example.org/');
print ' You'll be redirected in ten seconds ';
Of course, you can also use HTML syntax to implement
//
Header (' content-transfer-encoding:binary ');
Load the file to send:
ReadFile (' Example.zip ');
Disable caching for the current document
Header (' Cache-control:no-cache, No-store, max-age=0, Must-revalidate ');
Header (' Expires:mon, Jul 1997 05:00:00 GMT '); Date in the past
Header (' Pragma:no-cache ');
To set the content type:
Header (' content-type:text/html; charset=iso-8859-1 ');
Header (' content-type:text/html; Charset=utf-8 ');
Header (' Content-type:text/plain '); Plain Text Format
Header (' Content-type:image/jpeg '); JPG pictures
Header (' Content-type:application/zip '); ZIP file
Header (' content-type:application/pdf '); PDF file
Header (' Content-type:audio/mpeg '); Audio files
Header (' Content-type:application/x-shockwave-flash '); Flash Animation
Show Login dialog box
Header (' http/1.1 401 Unauthorized ');
Header (' Www-authenticate:basic realm= ' Top Secret ');
print ' Text that would be displayed if the user hits cancel or ';
print ' enters wrong login data ';
?>

http://www.bkjia.com/PHPjc/327496.html www.bkjia.com true http://www.bkjia.com/PHPjc/327496.html techarticle header () is the used to send raw HTTP headers. See the http/1.1 specification for more information on HTTP headers. Example one: Copy code code as follows:? PHP Header ("location:http:/ ...

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