Exploring the usage of headers in php _ PHP Tutorial

Source: Internet
Author: User
Explore the usage of headers in php. Header () isusedtosendrawHTTPheaders. SeetheHTTP1.1specificationformoreinformationonHTTPheaders. Example 1: Copy the code as follows :? PHPHeader (Location: http: Header()Is used to send raw HTTPHeaders. See the HTTP/1.1 specification for more information on HTTPHeaders.

Example 1:

The code is as follows:


Header ("Location: http://www.jb51.net ";);
Exit; // after each redirection, you must add "exit" to avoid errors and continue execution.
?>


The code is as follows:


Headers ("refresh: 2; url = http://www.jb51.net ");
Echo "Loading... please wait...
Jump to Baidu in three seconds ...";
?>


--------------------------------------------------------------------------------
Example 2: Disable page caching in IE
Make the viewer get the latest information every time, instead of the information in the Proxy or cache:

The code is as follows:


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 webpage on the server changes frequently, set Expires to-1, indicating that the page will expire immediately. If a webpage is updated at every day, you can set Expires to the next day. When CacheControl = no-cache is specified on the HTTP1.1 server, the browser does not cache the webpage.
The Cache-Control title cannot be used for legacy HTTP 1.0 servers. To be backward compatible with HTTP 1.0 servers, IE uses the Pragma: no-cache title to provide special support for HTTP. If the client communicates with the server through a secure connection (https: //) and the server returns the Pragma: no-cache title in the response, Internet Explorer does not cache the response.
Note: Pragma: no-cache prevents caching only when used in secure connections. if used on a non-secure page, the processing method is the same as Expires:-1, this 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 on the html page. Earlier versions of IE may not support html meta tags, so it is best to disable caching using the http message header.
--------------------------------------------------------------------------------
Example 3: make the user's browser unable to find the file information.
Write a lot of information on the Internet like this: the php function header () can send the Status header to the browser,
For example, header ("Status: 404 Not Found "). But in fact, the response returned by the browser is:

The code is as follows:


HTTP/1.x 200 OK
Date: Thu, 03 Aug 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


I checked some information. the correct method is:
Header ("http/1.1 404 Not Found ");
The first part is the HTTP Version, the second part is the Status code, and the third part is the Reason Phrase (Reason-Phrase ).
--------------------------------------------------------------------------------
Example 4: allow users to download files (hide the file location)
Html tags can be used to download common files. To keep files confidential, you can use the header function to download files.

The code is as follows:


Header ("Content-type: application/x-gzip ");
Header ("Content-Disposition: attachment; filename = file name /");
Header ("Content-Description: PHP3 Generated Data ");
?>


Example 4: input content before the header function
Generally, html content cannot be output before the header function. for example, there are setcookie () and session functions. these functions need to add message header information to the output stream. If an echo statement exists before the header () is executed, when header () is encountered later, "Warning: Cannot modify header information-headers already sent by…" is reported ...." Error. That is to say, there cannot be any text, blank lines, and carriage return before these functions, and it is best to add the exit () function after the header () function. For example, the following error code contains an empty line between two php code segments:

The code is as follows:


// Some code here
?>
// It should be a blank line
Header ("http/1.1 403 Forbidden ");
Exit ();
?>


The reason is:When the PHP script starts execution, it can send both the http message header (title) information and the subject information. the http message header (from header () or SetCookie () function) is not sent immediately. Instead, it is saved to a list. this allows you to modify the title information, including the default title (for example, Content-Type title ). however, once the script sends any non-title output (for example, called using HTML or print (), PHP must first send all headers and then terminate the HTTP Header. then send the subject data. at this time, any attempt to add or modify the Header information is not allowed, and one of the above error messages will be sent.
Solution:
Modify php. ini to open the cache (output_buffering), or use the cache functions ob_start () and ob_end_flush () in the program. Principle: when output_buffering is enabled, PHP does not send HTTP headers when the script sends the output. Instead, it inputs this output to the dynamically added cache through the pipeline (pipe) (which can only be used in PHP 4.0 and has a centralized output mechanism ). You can still modify/add the header or set the cookie 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 content in 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 ID to the URL so that it can read new content each time to avoid caching.
Example:

The code is as follows:


Print ""; // The cache file is normally read.
?>
Print ""; // adds a unique number to make the browser request again
W // print "";
?>


2: The following is a good function that transfers images to the browser for display.

The 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 instances:

The code is as follows:


// OK
Header ('http/1.1 200 OK ');
// Set a 404 header:
Header ('http/1.1 404 Not Found ');
// Set the 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 redirection:
Header ('refresh: 10; url = http://www.example.org /');
Print 'You will be redirected in 10 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, 26 Jul 1997 05:00:00 GMT'); // Date in the past
Header ('pragma: no-cache ');
// 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 image
Header ('content-Type: application/zip'); // zip file
Header ('content-Type: application/pdf '); // pdf file
Header ('content-Type: audio/mpeg '); // audio File
Header ('content-Type: application/x-shockwave-Flash'); // flash animation
// Display the login dialog box
Header ('http/1.1 401 unauthorized ');
Header ('www-Authenticate: Basic realm = "Top Secret "');
Print 'text that will be displayed if the user hits cancel or ';
Print 'enters wrong login data ';
?>

Http://www.bkjia.com/PHPjc/327496.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/327496.htmlTechArticleheader () is used to send raw HTTP headers. See the HTTP/1.1 specification for more information on HTTP headers. Example 1: the code is as follows :? PHP Header ("Location: http :/...

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.