PHP header usage

【Foreword】

   The purpose of the header() function is to send a raw HTTP header [Http Header] to the client.

   The header (header) is a string sent by the server before sending HTML data to the browser through HTTP protocol. A blank line is required to separate the header and the HTML file.

   All headers need to be passed before returning HTML data in PHP. The header() function sends raw HTTP headers to the client, it is important to realize that the header() function must be called before any actual output is sent

 

【main body】

Example 1: Redirect

 

<?PHP  
Header("Location: http://www.jb51.net";);   
exit;//"exit" must be added after each redirection to avoid errors and continue execution.  
?>  
  
<?php  
header("refresh:2;url=http://www.jb51.net");  
echo "Loading, please wait...<br>Automatically jump to <a href="..." mce_href="...">Baidu</a>..." after three seconds;  
?>  

 

 

Example 2: Forbid the page to be cached in IE 

So that the browser can get the latest data every time, instead of the data in Proxy or cache:

 

<?PHP  
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 web page on the server changes frequently, set Expires to -1, which means that it expires immediately. If a web page is updated at 1am every day, you can set Expires to be at 1am the next day. When the HTTP1.1 server specifies CacheControl=no-cache, the browser will not cache the page.

   Legacy 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 a Pragma:no-cache header in the response, Internet Explorer will not cache the response.

   Note: Pragma:no-cache prevents caching only when used in secure connections, if used in non-secure pages, the handler

The format 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 better to use http message headers to disable caching.

 

Example 3: Let the user's browser display the message that the file cannot be found. 

   A lot of information on the Internet is written like this: php's function header() can send a Status header to the browser,

   Such as header("Status: 404 Not Found"). But in fact the 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

   After checking some information, the correct way of writing 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 (Status); the third part is the reason phrase (Reason-Phrase).

 

Example 4: Let the user download the file (the location of the hidden file)

   html tags can achieve ordinary file download. If you want to keep the file secret, you can't tell others the file link, you can use the header function to download the file.

 

<?php  
header("Content-type: application/x-gzip");   
header("Content-Disposition: attachment; filename=filename/");   
header("Content-Description: PHP3 Generated Data");   
?>  

 

 

Example 4: Input content before the header function

   Generally speaking, the html content cannot be output before the header function. Similar to the setcookie() and session functions, these functions need to add message header information to the output stream. If there are statements such as echo before the execution of header(), when header() is encountered later, the error "Warning: Cannot modify header information - headers already sent by ...." 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, the following error is written, there is a blank line between the two php code snippets:

 

//some code here  
?>  
//This should be a blank line  
header(”http/1.1 403 Forbidden”);  
exit();  
?>  

   The reason is:

 

      When a PHP script starts executing, it can send both http message header (header) information and body information. The http message header (from the header() or SetCookie() functions) is not sent immediately, instead, it is saved to a list. This allows you to modify header information, including default headers (such as the Content-Type header). However, once the script sends any non-header output (eg, using HTML or a print() call), then PHP It is necessary to send all headers first, then terminate the HTTP header. Then continue to send the body data. From this point on, any attempt to add or modify 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(), 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 increasing cache (available only 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 the entire script terminates, PHP will automatically send HTTP headers to the browser, and then send the content of the output buffer.

 

When jumping with header("location:test.php") in PHP, pay attention to the following points :

1. There cannot be a space between location and ":", otherwise an error will occur.//phpfensi.com

2. There cannot be any output before the header is used, including no space after the label "?>" in the include page.

3. The PHP code after the header will also be executed.

   Before the PHP header jumps, there can be no content output, because PHP has already sent HTTP header information to the browser when it starts to execute, and it is no longer allowed to change after that.

   But if you must process the header information after output, you can use ob_start() ob_end_flush() to cache the content to be sent, and wait until the header continues to send the content.

Or a simpler way, modify php.ini, find output_buffering=Off and change it to output_buffering=4096.

 

PHP Manual Example Application

   1: You can use the heder command to force the browser to use fresh content (no caching).

You can also add a unique number to the URL so that it reads new content every time to avoid caching.

example:

 

<?  
print "<img src="cs.jpg" mce_src="cs.jpg">"; //usually read the cache file  
?>  
<?  
print "<img src="cs.jpg?".time()."" mce_src="cs.jpg?".time()."">";   
//Add a unique number to make the browser re-request  
w//print "<img src="cs.jpg?".rand(100,999)."" mce_src="cs.jpg?".rand(100,999)."">";   
?>

 

2: The following is a good function to send the image 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 examples:

<?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.baidu.com');  
//File delayed forwarding:  
header('Refresh: 10; url=http://www.example.org/');  
print 'You will be redirected in 10 seconds';  
//Of course, it can also be implemented using html syntax  
// <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 content length  
header('Content-Length: 1234');  
// set 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图片  
header('Content-Type: application/zip'); // ZIP文件  
header('Content-Type: application/pdf'); // PDF文件  
header('Content-Type: audio/mpeg'); // audio file  
header('Content-Type: application/x-shockwave-flash'); //Flash动画  
//Display the login dialog  
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';  
?>  

 

 

 

 

 

 

 

 

 

 

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326116193&siteId=291194637