PHP Header Application Details

Source: Internet
Author: User
Tags http authentication php website readfile setcookie



Usage of header

The function of the header () is to send an original HTTP header [HTTP header] to the client.

The header is a string sent by the server to the browser before the HTML data is transmitted to the HTTP, in the header

There is an empty line separating the HTML file. For a detailed description of HTTP, you can refer to RFC 2068 official documents


Before sending the HTML data back in PHP, you need to pass all the headers first.

Usage examples

Example one: This example redirects the browser to the official PHP website.

<? Php

Header ("location:";);

Exit After each redirect, "Exit" must be added to avoid an error and continue execution.



Header ("Refresh:3;url=");

Print (' Loading, please wait ...<br> three seconds after the automatic jump ~ ~ ~ ');

Header redirection is equivalent to entering a URL for the user in the Address bar


Example two: Prohibit pages from being cached in IE

To be able to get the most up-to-date information each time instead of the Proxy or cache, use the following headers

<? Php

Header (' Expires:mon, 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


Expires =-1

Expires is a good thing, if the Web page on the server changes frequently, it is set to 1, indicating immediate expiration. 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.


You can use HTTP-EQUIV meta to mark the header of the 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 Internet so write: Php function header () can send a status header to the browser,

such as the header ("status:404 not Found").

But I found that the response actually returned by the browser was:

http/1.x OK

Date:thu, 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



Check some information, the correct wording is:

Header ("http/1.1 404 Not Found");

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

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.


Header ("Content-type:application/x-gzip");

Header ("content-disposition:attachment; Filename= file name \ ");

Header ("Content-description:php3 Generated Data");


Example four: input content before header function

In general, you cannot 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 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:

Some code here


This is supposed to be a blank line.

Header ("http/1.1 403 Forbidden");

Exit ();


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.


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.


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 number to the URL so that it reads new content every time and avoids caching.



Print "



Print " "; Added a unique number to make the browser request again

W//print " ";


2: Here is a good function to send the picture to the browser display.


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:



Header (' http/1.1 OK ');

Set a 404 Header:

Header (' http/1.1 404 Not Found ');

Set address to be permanently redirected

Header (' http/1.1 301 Moved permanently ');

Go to a new address

Header (' location:');

File Delay Steering:

Header (' refresh:10; url=');

print ' You'll be redirected in ten seconds ';

Of course, you can also use HTML syntax to implement

<meta http-equiv= "Refresh" content= "10;>

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 ');

Tell 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 as a download type

Header (' Content-type:application/octet-stream ');

Header (' content-disposition:attachment; filename= ' ');

Header (' content-transfer-encoding:binary ');

Load the file to send:

ReadFile (' ');

Disable caching for the current document

Header (' Cache-control:no-cache, No-store, max-age=0, Must-revalidate ');

Header (' Expires:mon, Jul 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 would be displayed if the user hits cancel or ';

print ' enters wrong login data ';


From the Sunrise Network

The header () function sends the original HTTP header to the client, mainly including the version of the HTTP protocol, the status code, the reason phrase, etc. we often use for the jump page, status send and file download, let's take a look.

The header is divided into three parts:

The first part is the version of the HTTP Protocol (http-version);
The second part is state code (status);
The third part is the reason phrase (reason-phrase).

The header () function uses the description:

First, the role:
PHP only in the HTTP protocol to the HTML document header to the browser, tell the browser how to deal with this page, as for the content of the transfer will need to familiarize yourself with the HTTP protocol, not related to PHP, can refer to
The traditional header must contain one of the following three headers and can only occur once.
status:nnn xxxxxx

Second, first to understand how the HTTP protocol works
The HTTP protocol is based on the request/response paradigm. After a client establishes a connection to the server, it sends a request to the server in the form of a Uniform Resource Identifier, protocol version number, followed by MIME information including the request modifier, client information, and possible content. After the server receives the request, it gives the corresponding response information in the form of a status line that includes the protocol version number of the information, a successful or incorrect code, followed by MIME information including server information, entity information, and possible content.
It is divided into four processes, in the HTTP protocol, the server is the part that provides the HTTP service, the client refers to the browser you use or download tools and so on. In the communication, the client makes a request connection, the server establishes the connection, and then the client makes an HTTP request (request) and the server returns the response information (Respond), thus completing an HTTP operation.

Third, the meaning of the HTTP protocol status Code representation
1XX reserved
2XX indicates that the request was successfully received by
3XX request further refinement of requests for completion of customer requests
4XX Customer Error
5XX Server Error


The code is as follows
Copy Code

Fix 404 Pages: Use this header command to resolve the 404 header generated by URL rewriting
Header (' http/1.1 OK ');

Set 404 Header: Page not found
Header (' http/1.1 404 Not Found ');

Page is permanently deleted, can tell seo/seo.html "target=" _blank "> Search engine update their URLs
Set Moved permanently header (Good for redrictions)
Use with location header
Header (' http/1.1 301 Moved permanently ');
Restricted access
Header (' http/1.1 403 Forbidden ');
Server error
Header (' http/1.1 Internal Server Error ');

Redirect to a new location
Redirect to a new location:
Header (' location: ');

Redirect after a period of delay
Redrict with delay:
Header (' refresh:10; url= ');
print ' You'll be redirected in ten seconds ';

Overwrite x-powered-by value
Override x-powered-by:php:
Header (' x-powered-by:php/4.4.0′ ');
Header (' x-powered-by:brain/0.6b ');

Content language (en = 中文版)
Content language (en = 中文版)
Header (' content-language:en ');

Last modified time (can be used when caching)
Last modified (good for caching)
$time = time () –60; or Filemtime ($FN), etc
Header (' last-modified: '. Gmdate (' d, D M Y h:i:s ', $time). ' GMT ');

Tell the browser what to get is not updated
Header for telling the browser the content
did not get changed
Header (' http/1.1 304 not Modified ');

Set the length of the content (can be used when caching):
Set content Length (good for caching):
Header (' content-length:1234′ ');

To download files:
Headers for an download:
Header (' Content-type:application/octet-stream ');
Header (' content-disposition:attachment; filename= ' ');
Header (' content-transfer-encoding:binary ');

Disable caching of the current document:
Load the file to Send:readfile (' ');
Disable caching of the current document:
Header (' Cache-control:no-cache, No-store, max-age=0, Must-revalidate ');
Header (' Expires:mon, Jul 1997 05:00:00 GMT ');
To set the content type:
Date in the Pastheader (' Pragma:no-cache ');
Set 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 file
Header (' Content-type:image/jpeg ');

JPG picture
Header (' Content-type:application/zip ');

ZIP file
Header (' content-type:application/pdf ');

PDF file
Header (' Content-type:audio/mpeg ');

Audio MPEG (MP3,...) file
Header (' Content-type:application/x-shockwave-flash ');

Displays the Login dialog box, which can be used for HTTP authentication
Flash animation//show Sign In box
Header (' http/1.1 401 Unauthorized ');
Header (' Www-authenticate:basic realm= ' Top Secret ');
print ' Text that would be displayed if the user hits cancel or ';
print ' Enters wrong login da
Ta ';

Now fill out the form, we can use Ajax to the user at any time to verify, friendly hints, but in the user did not pay attention to the Ajax friendly prompts, submitted the wrong form, jumped back to the original page, and fill in the information is all lost. To support page bounce, you have the following options:
1. Use the Session_cache_limiter method: Session_cache_limiter (' private,must-revalidate '); but it should be noted that Session_cache_limiter () The method must be written before the Session_Start () method is used;
2. Use the header to set the control cache method: Header (' cache-control:private,must-revalidate ');

Summary of several problems to be noticed in page jump

1, location and ":" No space between, otherwise it will be wrong.
2, before using the header can not have any output.
3. The PHP code after the header will also be executed.

PHP Header Application Details

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.