phoenixg / header_http_status_codes.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/* |
参考自: |
http://darklaunch.com/2010/09/01/http-status-codes-in-php-http-header-response-code-function |
http://snipplr.com/view/68099/ |
*/ |
function HTTPStatus ( $ num ) |
$ http = array ( |
100 => ‘HTTP/1.1 100 Continue’ , |
101 => ‘HTTP/1.1 101 Switching Protocols’ , |
200 => ‘HTTP/1.1 200 OK’ , |
201 => ‘HTTP/1.1 201 Created’ , |
202 => ‘HTTP/1.1 202 Accepted’ , |
203 => ‘HTTP/1.1 203 Non-Authoritative Information’ , |
204 => ‘HTTP/1.1 204 No Content’ , |
205 => ‘HTTP/1.1 205 Reset Content’ , |
206 => ‘HTTP/1.1 206 Partial Content’ , |
300 => ‘HTTP/1.1 300 Multiple Choices’ , |
301 => ‘HTTP/1.1 301 Moved Permanently’ , |
302 => ‘HTTP/1.1 302 Found’ , |
303 => ‘HTTP/1.1 303 See Other’ , |
304 => ‘HTTP/1.1 304 Not Modified’ , |
305 => ‘HTTP/1.1 305 Use Proxy’ , |
307 => ‘HTTP/1.1 307 Temporary Redirect’ , |
400 => ‘HTTP/1.1 400 Bad Request’ , |
401 => ‘HTTP/1.1 401 Unauthorized’ , |
402 => ‘HTTP/1.1 402 Payment Required’ , |
403 => ‘HTTP/1.1 403 Forbidden’ , |
404 => ‘HTTP/1.1 404 Not Found’ , |
405 => ‘HTTP/1.1 405 Method Not Allowed’ , |
406 => ‘HTTP/1.1 406 Not Acceptable’ , |
407 => ‘HTTP/1.1 407 Proxy Authentication Required’ , |
408 => ‘HTTP/1.1 408 Request Time-out’ , |
409 => ‘HTTP/1.1 409 Conflict’ , |
410 => ‘HTTP/1.1 410 Gone’ , |
411 => ‘HTTP/1.1 411 Length Required’ , |
412 => ‘HTTP/1.1 412 Precondition Failed’ , |
413 => ‘HTTP/1.1 413 Request Entity Too Large’ , |
414 => ‘HTTP/1.1 414 Request-URI Too Large’ , |
415 => ‘HTTP/1.1 415 Unsupported Media Type’ , |
416 => ‘HTTP/1.1 416 Requested Range Not Satisfiable’ , |
417 => ‘HTTP/1.1 417 Expectation Failed’ , |
500 => ‘HTTP/1.1 500 Internal Server Error’ , |
501 => ‘HTTP/1.1 501 Not Implemented’ , |
502 => ‘HTTP/1.1 502 Bad Gateway’ , |
503 => ‘HTTP/1.1 503 Service Unavailable’ , |
504 => ‘HTTP/1.1 504 Gateway Time-out’ , |
505 => ‘HTTP/1.1 505 HTTP Version Not Supported’ , |
); |
header( $ http [ $ num ]); |
return |
array ( |
‘code’ => $ num , |
‘error’ => $ http [ $ num ], |
); |
> |
///////////////////////////////////////////////////////////////////////// |
// HTTP HEADER STATUS CODES |
header( ‘HTTP/1.1 200 OK’ ); |
header( ‘HTTP/1.1 404 Not Found’ ); |
header( ‘HTTP/1.1 403 Forbidden’ ); |
header( ‘HTTP/1.1 301 Moved Permanently’ ); |
header( ‘HTTP/1.1 304 Not Modified’ ); |
header( ‘HTTP/1.1 500 Internal Server Error’ ); |
header( ‘Location: http://www.example.org/’ ); |
header( ‘Refresh: 10; url=http://www.example.org/’ ); |
print ‘You will be redirected in 10 seconds’ ; |
// you can also use the HTML syntax: |
// |
// override X-Powered-By value |
header( ‘X-Powered-By: PHP/4.4.0’ ); |
// content language (en = English) |
header( ‘Content-language: en’ ); |
// last modified (对缓存友好) |
$ time = time() — 60 ; // or filemtime($fn), etc |
header( ‘Last-Modified: ‘ .gmdate( ‘D, d M Y H:i:s’ , $ time ). ‘ GMT’ ); |
// set content length (对缓存友好): |
header( ‘Content-Length: 1234’ ); |
// Headers for an download: |
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 of 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 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’ ); // Flash animation |
// show sign in 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 enters wrong login data’ ; |
header
header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include , or require , functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
/* This will give an error. Note the output
* above, which is before the header() call */
header ( ‘Location: http://www.example.com/’ );
exit;
?>
Parameters
There are two special-case header calls. The first is a header that starts with the string » HTTP/ » (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.
// This example illustrates the «HTTP/» special case
// Better alternatives in typical use cases include:
// 1. header($_SERVER[«SERVER_PROTOCOL»] . » 404 Not Found»);
// (to override http status messages for clients that are still using HTTP/1.0)
// 2. http_response_code(404); (to use the default message)
header ( «HTTP/1.1 404 Not Found» );
?>?php
The second special case is the «Location:» header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.
header ( «Location: http://www.example.com/» ); /* Redirect browser */
?php
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in false as the second argument you can force multiple headers of the same type. For example:
Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the header is not empty.
Return Values
Errors/Exceptions
On failure to schedule the header to be sent, header() issues an E_WARNING level error.
Examples
Example #1 Download dialog
If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.
// We’ll be outputting a PDF
header ( ‘Content-Type: application/pdf’ );
?php
// It will be called downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );
// The PDF source is in original.pdf
readfile ( ‘original.pdf’ );
?>
Example #2 Caching directives
PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:
header ( «Cache-Control: no-cache, must-revalidate» ); // HTTP/1.1
header ( «Expires: Sat, 26 Jul 1997 05:00:00 GMT» ); // Date in the past
?>?php
Note:
You may find that your pages aren’t cached even if you don’t output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.
Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.
Notes
Note:
Headers will only be accessible and output when a SAPI that supports them is in use.
Note:
You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.
Note:
The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.
Note:
Most contemporary clients accept relative URI s as argument to » Location:, but some older clients require an absolute URI including the scheme, hostname and absolute path. You can usually use $_SERVER[‘HTTP_HOST’] , $_SERVER[‘PHP_SELF’] and dirname() to make an absolute URI from a relative one yourself:
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER [ ‘HTTP_HOST’ ];
$uri = rtrim ( dirname ( $_SERVER [ ‘PHP_SELF’ ]), ‘/\\’ );
$extra = ‘mypage.php’ ;
header ( «Location: http:// $host$uri / $extra » );
exit;
?>?php
Note:
Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.
See Also
- headers_sent() — Checks if or where headers have been sent
- setcookie() — Send a cookie
- http_response_code() — Get or Set the HTTP response code
- header_remove() — Remove previously set headers
- headers_list() — Returns a list of response headers sent (or ready to send)
- The section on HTTP authentication
- Network Functions
- checkdnsrr
- closelog
- dns_check_record
- dns_get_mx
- dns_get_record
- fsockopen
- gethostbyaddr
- gethostbyname
- gethostbynamel
- gethostname
- getmxrr
- getprotobyname
- getprotobynumber
- getservbyname
- getservbyport
- header_register_callback
- header_remove
- header
- headers_list
- headers_sent
- http_response_code
- inet_ntop
- inet_pton
- ip2long
- long2ip
- net_get_interfaces
- openlog
- pfsockopen
- setcookie
- setrawcookie
- socket_get_status
- socket_set_blocking
- socket_set_timeout
- syslog