Detailed analysis of PHP header Functions

Source: Internet
Author: User
Tags php website

The Header () function sends an original HTTP header [HTTP header] to the client.

The header is the string sent by the server before the server passes HTML data to the browser with HTTP co-meaning.

Separate HTML files with a blank line. For more information about HTTP, see the RFC 2068 official file.

Http://www.w3.org/Protocols/rfc2068/rfc2068 ).

Before sending HTML data back to PhP, you must upload all the headers.

Example

Example 1: In this example, the browser is redirected to the official PHP website.

<? PHP

Header ("Location: http://www.php.net ";);

Exit; // after each redirection, you must add "exit" to avoid errors and continue execution.

?>

<? PHP

/**

@ Title: PhP timed jump

@ Function: Wait for the specified time and jump to the specified page (instead of HTML Meta)

*/

Headers ("Refresh: 3; url = http://axgle.za.net ");

Print ('loading, please wait... <br> automatically jump in 3 seconds ~~~ ');

/*

Note:

If the wait time is 0, it is equivalent to Header ("Location.

*/

Header redirection is equivalent to inputting a URL in the address bar for the user.

?>

Example 2: Disable page caching in IE

To obtain the latest data every time, instead of the data in the proxy or cache, you can use the following Header

<? PHP

Header ('expires: Mon, 26 Jul 1997 05: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

Expires is a good stuff. If the webpage on the server changes frequently, set it to-1, indicating that it 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 ").

However, I found that the actual response returned by the browser is:

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.

<? PHP

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. Similarly, 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:

// Some code here

?>

// It should be a blank line

Header ("HTTP/1.1 403 Forbidden ");

Exit ();

?>

The original cause is that when the PHP script starts to be executed, 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 function 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:

<?

Print "

?>

<?

Print " "; // adds a unique ID to make the browser send a new request.

W // print " ";

?>

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

<? PHP

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:

<? PHP

// 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.example.org /');

// 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

// <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 the last modification time

$ Time = Time ()-60; // or filemtime ($ FN), etc

Header ('Last-modified: '. gmdate ('d, D m y h: I: s', $ time). 'gmt ');

// Tell the browser that the document content has not changed

Header ('HTTP/1.1 304 not modified ');

// Set the Content Length

Header ('content-length: 1234 ');

// Set it 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, 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 ';

?>

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.