Discuss the usage of header in php

  • 2020-06-07 04:08:10
  • OfStack

header() is used to send raw HTTP headers. See the HTTP/1.1 specification for more information on HTTP headers.

Example 1:

Header("Location: https://www.ofstack.com";); 
exit;// You have to add "after every redirect." exit", After avoiding an error, proceed. 

echo " Please wait while loading ...<br>3 Automatically jump to after seconds <a href="https://www.ofstack.com" mce_href="https://www.ofstack.com"> baidu </a>...";

Example 2: Disable caching of pages in IE
So that visitors can get the latest information every time, instead of Proxy or cache:

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 pages on the server change frequently, set Expires to -1 to indicate immediate expiration. If a page is updated at 1am every day, Expires can be set to 1am the next day. When es21EN1.1 server specifies CacheControl = no-ES24en, the browser does not cache the page.
Older HTTP 1.0 servers cannot use es27EN-ES28en titles. So for backward compatibility with HTTP 1.0 servers, IE provides special support for HTTP using the Pragma: ES32en-ES33en title. If the client communicates with the server via a secure connection (https://) and the server returns the Pragma: ES37en-ES38en title in the response, Internet Explorer does not cache this response.
Note: Pragma: ES43en-ES44en prevents caching only when used in secure connections. If used in non-secure pages, the page will be cached but marked as immediately out of date.
http-equiv meta Mark:
On the html page, you can use http-ES53en meta to tag the specified http message header. Older versions of IE may not support the html meta tag, so it is best to use http message headers to disable caching.
Example 3: Make the user's browser display information that the file could not be found.
header(), a function of php, sends the Status header to the browser,
header(" Status: 404 Not Found "). But in reality, the browser's response 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

The correct way to write it is as follows:
header (" http / 1.1 404 Not Found ");
Part 1 is the version of THE HTTP protocol (HTTP-ES83en); Part 2 is the status code (Status); Part 3 is the reason phrase (ES85en-ES86en).
Example 4: Let the user download the file (hide the location of the file)
The html tag can be used to download normal files. If you cannot link to a file for confidentiality, you can use the header function to download the file.

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

Example 4: Input before the header function
In general, html content cannot be printed before the header function, like the setcookie() and session functions, which need to add message headers to the output stream. If there is a statement such as echo before the execution of header(), when header() is encountered, it will be reported as "Warning: modify header ES109en-ES111en by... "Error. This means that these functions must not be preceded by any text, blank lines, carriage returns, etc., and it is best to add the exit() function to the header() function. For example, the following error has a blank line between two php code segments:

//some code here
// This should be 1 A blank line 
header( " http/1.1 403 Forbidden " );

The reason is: PHP script starts, it can be sent at the same time http message header information and the main body (title). http message header (from header () or SetCookie () function) will not be sent immediately, on the contrary, it is saved to a list. This will allow you to modify the header information, including the default title (such as Content - Type title). However, as the script has sent any title not output (for example, using HTML or print () ), then PHP must first send all Header, then terminate HTTP header, and then continue sending the body data. From this point on, any attempt to add or modify Header information is not allowed and sends the error message 1 above.
Modify php.ini to turn on the cache (output_buffering), or use the cache functions ob_start(), ob_end_flush() in your program. The principle is that when output_buffering is enabled, PHP does not send HTTP header when the script sends output. Instead, it piped this output (pipe) into the dynamically increased cache (available only in PHP 4.0, which has a centralized output mechanism). You can still modify/add header, or set cookie, as header is not actually sent. When all scripts terminate, PHP automatically sends HTTP header to the browser and then sends the contents of the output buffer.
Example application of PHP manual
1: You can use the heder command to force the browser to use fresh content (no cache).
You can also add a unique 1 number to the url so that it reads the new content each time, avoiding caching.

print "<img src="cs.jpg" mce_src="cs.jpg">";   // Typically, cache files are read 
print "<img src="cs.jpg?".time()."" mce_src="cs.jpg?".time()."">";   // Increased only 1 Makes the browser request again 
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.

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;
    return false;

More examples:

// ok
header('HTTP/1.1 200 OK');
// Set up the 1 a 404 head :
header('HTTP/1.1 404 Not Found');
// Set the address to be permanently redirected 
header('HTTP/1.1 301 Moved Permanently');
// Go to the 1 A new address 
header('Location: http://www.baidu.com');
// File delay steering :
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';
// Of course, you can use it html The syntax to achieve 
// <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');
// The document language 
header('Content-language: en');
// Tell the browser at the end 1 Secondary 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 1 10 Download types 
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"'); 
header('Content-Transfer-Encoding: binary');
// load the file to send:
//  Disable caching for current documents 
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 The picture 
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 
// Displays 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';

Related articles: