Home > Backend Development > PHP Tutorial > Detailed explanation of usage examples of header function in php

Detailed explanation of usage examples of header function in php

WBOY
Release: 2016-07-25 08:59:04
Original
921 people have browsed it
  1. Header("Location: http://bbs.it-home.org";);
  2. exit;//Add "exit" after each redirect to avoid After an error occurs, execution continues.
  3. ?>
Copy code

2,

  1. header("refresh:2;url=http://bbs.it-home.org");
  2. echo "Loading, please wait...
    Automatically jump toProgrammer's Home?>
Copy code

Example 2: Disable page caching in IE So that viewers can get the latest content every time, instead of the data in Proxy or cache:

  1. header( 'Expires: Fri, 4 Dec 2009 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 pages on the server change frequently, set Expires to -1, indicating immediate expiration. If a web page is updated at 1 am every day, you can set Expires to 1 am the next day. When the HTTP1.1 server specifies CacheControl = no-cache, the browser will not cache the web page.

Old HTTP 1.0 servers cannot use the Cache-Control header. So for backward compatibility with HTTP 1.0 servers, IE provides special support for HTTP using the Pragma:no-cache header. If the client communicates with the server over a secure connection (https://) and the server returns the Pragma:no-cache header in the response, Internet Explorer does not cache the response. Note: Pragma:no-cache only prevents caching when used in a secure connection. If used in a non-secure page, the handling is the same as Expires:-1. The page will be cached but marked as expired immediately.

http-equiv meta tag: You can use http-equiv meta to mark the specified http message header in the html page. Older versions of IE may not support html meta tags, so it's best to use http message headers to disable caching.

Example 3: Let the user's browser display a message that the file cannot be found. A lot of information on the Internet says this: PHP’s function header() can send the Status header to the browser. Such as header("Status: 404 Not Found"). But the actual response returned by the browser is:

  1. header("http/1.1 404 Not Found");
Copy code

The first part is the HTTP protocol version (HTTP-Version); the second part is the status code (Status); The third part is Reason-Phrase.

Example 4: Allow users to download files (hidden file location) The html tag can be used to download ordinary files. If you want to keep the file confidential and you cannot tell others the file link, you can use the header function to download the file.

  1. header("Content-type: application/x-gzip");
  2. header("Content-Disposition: attachment; filename=filename/");
  3. header("Content- Description: PHP3 Generated Data");
  4. ?>
Copy code

Example 4: Input content before header function Generally speaking, HTML content cannot be output before the header function. Similarly, there are setcookie() and session functions. These functions need to add message header information to the output stream. If there are statements such as echo before header() is executed, when header() is encountered later, a "Warning: Cannot modify header information - headers already sent by ...." error will be reported. That is to say, 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 incorrect writing, there is a blank line between the two PHP code snippets:

  1. //some code here
  2. ?>
  3. //This should be a blank line
  4. header("http/1.1 403 Forbidden");
  5. exit();
Copy code

?>

The reason is: when the PHP script starts executing, it can send the http message header (title) information and the body information at the same time. The http message header (from the header() or SetCookie() function) is not sent immediately, on the contrary, it is saved to a list. This allows you to modify the header information, including the default header (e.g. Content-Type header). However, once the script sends any non-header output (e.g. using HTML or a print() call ), then PHP must first send all Headers, then terminate the HTTP header. Then continue to send the main data. From this point on, any attempt to add or modify Header information is not allowed, and the above error message will be sent one.

Solution: Modify php.ini to turn on caching (output_buffering), or use the caching functions 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 pipes this output into a dynamically growing cache (only available in PHP 4.0, which has a centralized output mechanism). You can still modify/add headers, or set cookies, since headers are not actually sent. When all scripts terminate, PHP will automatically send HTTP headers to the browser, and then send the contents of the output buffer.

Introducing a few small examples of header functions in the PHP manual.

1. Use the heder command to force the browser to use fresh content (no caching). A unique number is added to the URL so that it reads new content every time and avoids caching.

  1. print ""; //Usually the cache file is read
  2. ?>
  3. print ""; //Added a unique number to enable browsing The server re-requests
  4. w//print "";
  5. ? >
Copy the code

2 to send the image to the browser for display. ? & Lt;? Php

function pe_img_by_path ($ pe_imgpath = "") {
IF (File_exists ($ PE_IMGPATH)) {
$ pe_imgarray = PATHINFO ($ PE_IMGPATH);
    $ iconContent = FILE_GET_CONTENTS ($ PE_IMGPATH );
  1. header("Content-type: image/" . $PE_imgarray["extension"]);
  2. header('Content-length: ' . strlen($iconcontent));
  3. echo $iconcontent;
  4. die(0) ;
  5. }
  6. return false;
  7. }
  8. ?>
  9. Copy code
  10. Attached is a complete and comprehensive application example of the header function.

    1. // ok
    2. header('HTTP/1.1 200 OK');
    3. //Set a 404 header:
    4. header('HTTP/1.1 404 Not Found');
    5. // Set the 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 Delayed redirection:
    10. header('Refresh: 10; url=http://www.example.org/');
    11. print 'You will be redirected in 10 seconds';
    12. //Of course, it can also be implemented using html syntax
    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, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    20. header('Pragma: no-cache');
    21. //Set 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 image
    26. header('Content-Type: application/zip'); / / ZIP file
    27. header('Content-Type: application/pdf'); // PDF file
    28. header('Content-Type: audio/mpeg'); // Audio file
    29. header('Content-Type: application/x -shockwave-flash'); //Flash animation
    30. //Display login dialog box
    31. header('HTTP/1.1 401 Unauthorized');
    32. header('WWW-Authenticate: Basic realm="Top Secret"');
    33. print 'Text that will be displayed if the user hits cancel or ';
    34. print 'enters wrong login data';
    35. ?>
    Copy code


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