An example of the use of header functions in PHP

Source: Internet
Author: User
Tags setcookie
    1. Header ("location:http://bbs.it-home.org";);
    2. exit;//add "Exit" after each redirect to avoid errors and continue execution.
    3. ?>
Copy Code

2,

    1. Header ("refresh:2;url=http://bbs.it-home.org");
    2. echo "Loading, please wait ...
      Automatically jump to the programmer's home after three seconds ... ";
    3. ?>
Copy Code

Example two: Prohibit the page in IE cache so that the browser can always get the latest content, instead of the Proxy or cache data:

    1. Header (' Expires:fri, 4 Dec 09:00:00 GMT ');
    2. Header (' last-modified: '. Gmdate (' d, D M Y h:i:s '). ' GMT ');
    3. Header (' Cache-control:no-store, No-cache, Must-revalidate ');
    4. Header (' cache-control:post-check=0, pre-check=0 ', false);
    5. Header (' Pragma:no-cache '); Compatible with http1.0 and HTTPS
    6. ?>
Copy Code

CacheControl = No-cache Pragma=no-cache Expires = 1 if the Web page on the server changes frequently, set the 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 tag: You can use HTTP-EQUIV meta to mark the header of a 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 Web this: 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:

    1. Header ("http/1.1 404 Not Found");
Copy Code

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 file (the location of hidden files) 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.

    1. Header ("Content-type:application/x-gzip");
    2. Header ("content-disposition:attachment; Filename= file name/");
    3. Header ("Content-description:php3 Generated Data");
    4. ?>
Copy Code

Example four: the header function before the input content in general, before the header function can not output HTML content, similar to the Setcookie () and the session function, these functions need to increase the message header information in 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:

    1. Some code here
    2. ?>
    3. This is supposed to be a blank line.
    4. Header ("http/1.1 403 Forbidden");
    5. Exit ();
Copy Code

?>

The reason: 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.

Introduces a small example of the header function in several PHP manuals.

1, use the Heder command to force the browser to use fresh content (no cache). Add a unique number to the URL so that it reads new content every time, avoiding caching.

    1. Print ""; The cache file is usually read
    2. ?>
    3. Print ""; Added a unique number to make the browser request again
    4. W//print "";
    5. ?>
Copy Code

2, send the picture to the browser display.

    1. function Pe_img_by_path ($PE _imgpath = "")
    2. {
    3. if (file_exists ($PE _imgpath)) {
    4. $PE _imgarray = pathinfo ($PE _imgpath);
    5. $iconcontent = file_get_contents ($PE _imgpath);
    6. Header ("content-type:image/". $PE _imgarray["extension"]);
    7. Header (' Content-length: '. strlen ($iconcontent));
    8. Echo $iconcontent;
    9. Die (0);
    10. }
    11. return false;
    12. }
    13. ?>
Copy Code

Attached, a complete and comprehensive example of the application of the header function.

  1. Ok
  2. Header (' http/1.1 OK ');
  3. Set a 404 Header:
  4. Header (' http/1.1 404 Not Found ');
  5. Set address to be permanently redirected
  6. Header (' http/1.1 301 Moved permanently ');
  7. Go to a new address
  8. Header (' location:http://www.baidu.com ');
  9. File Delay Steering:
  10. Header (' refresh:10; url=http://www.example.org/');
  11. print ' You'll be redirected in ten seconds ';
  12. Of course, you can also use HTML syntax to implement
  13. //
  14. Header (' content-transfer-encoding:binary ');
  15. Load the file to send:
  16. ReadFile (' Example.zip ');
  17. Disable caching for the current document
  18. Header (' Cache-control:no-cache, No-store, max-age=0, Must-revalidate ');
  19. Header (' Expires:mon, Jul 1997 05:00:00 GMT '); Date in the past
  20. Header (' Pragma:no-cache ');
  21. To set the content type:
  22. Header (' content-type:text/html; charset=iso-8859-1 ');
  23. Header (' content-type:text/html; Charset=utf-8 ');
  24. Header (' Content-type:text/plain '); Plain Text Format
  25. Header (' Content-type:image/jpeg '); JPG pictures
  26. Header (' Content-type:application/zip '); ZIP file
  27. Header (' content-type:application/pdf '); PDF file
  28. Header (' Content-type:audio/mpeg '); Audio files
  29. Header (' Content-type:application/x-shockwave-flash '); Flash Animation
  30. Show Login dialog box
  31. Header (' http/1.1 401 Unauthorized ');
  32. Header (' Www-authenticate:basic realm= ' Top Secret ');
  33. print ' Text that would be displayed if the user hits cancel or ';
  34. print ' enters wrong login data ';
  35. ?>
Copy Code
  • 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.