Explore the usage of header in PHP _php tips

Source: Internet
Author: User
Tags php script setcookie
header ()is used to send raw HTTPHeaders. The http/1.1 specification for more information onHTTPHeaders.

Example One:
Copy Code code as follows:

? Php
Header ("location:http://www.jb51.net";);
exit;//must add "exit" after each redirect to avoid an error and continue execution.

Copy Code code as follows:

Header ("Refresh:2;url=http://www.jb51.net");
echo "is loading, please wait ...<br> three seconds to automatically jump to <a href=" http://www.jb51.net "mce_href=" http://www.jb51.net "> Baidu </a ";..";

Example two: Prevent the page from being cached in IE
Enable visitors to get the latest information each time, rather than Proxy or cache data:
Copy Code code as follows:

? Php
Header (' Expires:fri, 4 Dec 2009 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 page on the server changes frequently, set the expires to-1, which means that it expires immediately. If a page is updated daily 1 o'clock in the morning, you can set the 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 Web page.
Legacy HTTP 1.0 Servers cannot use Cache-control headers. So for backward 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 through a secure connection (https://) and the server returns Pragma:no-cache headers in the response.
Note: Pragma:no-cache only prevents caching when used in a secure connection, and if used in an unsecured page, the processing is the same as expires:-1, and the page is cached but marked as immediately expired.
In an HTML page, you can use the HTTP-EQUIV meta to mark the header of the specified HTTP message. Older versions of IE may not support HTML meta tags, so it is a good idea to disable caching using the HTTP message headers.
Example Three: Let the user's browser appear to be unable to find the file information.
A lot of information on the Internet to write: Php function header () can send the status header to the browser,
such as header ("status:404 not Found"). But actually the response returned by the browser is:
Copy Code code as follows:

http/1.x OK
Date:thu, Aug 2006 07:49:11 GMT
server:apache/2.0.55 (WIN32) php/5.0.5
status:404 not Found
Keep-alive:timeout=15, max=98

After some information, the correct wording is:
Header ("http/1.1 404 Not Found");
The first part is the version of HTTP Protocol (http-version), the second part is state code (status), and the third part is the reason phrase (reason-phrase).
Example four: let users download files (location of hidden files)
HTML tags can be used to achieve normal file downloads. If you want to keep a confidential file, you cannot tell the file link to others, you can use the header function to achieve file download.
Copy Code code as follows:

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

example four: input before header function
In general, it is not possible to 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 header () executes, when the header () is encountered, the "Warning:cannot Modify header Information-headers already sent by ..." error is reported. This means that there can be no text, blank lines, carriage returns, etc. before 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 two PHP code snippets:
Copy Code code as follows:

Some code here
This is supposed to be a blank line.
Header ("http/1.1 403 Forbidden");
Exit ();

The reason is:When the PHP script starts executing, it can simultaneously send the HTTP message header (header) information and the principal information. The HTTP message header (from the header () or Setcookie () function) is not sent immediately, instead, it is saved to a list. This allows you to modify the header information, including the default headings (such as content-type headings). However, once the script sends any non-caption output (for example, using HTML or print () calls), then PHP must first send all headers and then terminate HTTP header. Then continue sending the principal data. From this point on, any attempt to add or modify header information is disallowed and sends one of the above error messages.
Modify the php.ini open 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 HTTP headers when the script sends output. Instead, it enters the output through the pipeline (pipe) into the dynamically incremented cache (which can only be used in PHP 4.0, which has a centralized output mechanism). You can still modify/add headers, or set cookies, because the header is not actually sent. When all 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 caching).
You can also add a unique number to the URL so that it reads the new content each time, avoiding caching.
Copy Code code as follows:

Print "?>
Print " "; Added a unique number to make the browser request again
W//print " ";

2: The following is a good function to send pictures to the browser display.
Copy Code code 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 Code code as follows:

Header (' http/1.1 OK ');
Set a 404-head:
Header (' http/1.1 404 Not Found ');
Set addresses to be permanently redirected
Header (' http/1.1 moved Permanently ');
Go to a new address
Header (' location:http://www.baidu.com ');
File delay turn:
Header (' refresh:10; url=http://www.example.org/');
print ' You'll be redirected in seconds ';
Of course, you can also use HTML syntax to implement
<meta http-equiv= "Refresh" content= "10;http://www.example.org//>
Override x-powered-by:php:
Header (' x-powered-by:php/4.4.0 ');
Header (' x-powered-by:brain/0.6b ');
Document language
Header (' content-language:en ');
Tell the browser when it was last modified
$time = time ()-60; or Filemtime ($FN), etc
Header (' last-modified: ' Gmdate (' d, D M Y h:i:s ', $time). ' GMT ');
Tells the browser that the contents of the document have not changed
Header (' http/1.1 304 not Modified ');
Set Content length
Header (' content-length:1234 ');
Set to a download type
Header (' Content-type:application/octet-stream ');
Header (' content-disposition:attachment; filename= "Example.zip");
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, June 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'll be displayed if the user hits cancel or ';
print ' enters wrong login data ';
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.