![]() |
7.5. Setting Response Headers
Aswe"ve already discussed, the HTTP response that aserver sends back to a client contains headers that identify the typeof content in the body of the response, the server that sent theresponse, how many bytes are in the body, when the response was sent,etc. PHP and Apache normally take care of the headers for you,identifying the document as HTML, calculating the length of the HTMLpage, and so on. Most web applications never need to set headersthemselves. However, if you want to send back somethingthat"s not HTML, set the expiration time for a page,redirect the client"s browser, or generate aspecific HTTP error, you"ll need to use theheader( ) function.
Bạn đang xem: How to set headers correctly in php
The only catch to setting headers is that you must do so before anyof the body is generated. This means that all calls toheader( ) (or setcookie( ),if you"re setting cookies) must happen at the verytop of your file, even before the tag. For example:
Date: todayFrom: fredTo: barneySubject: hands off! My lunchbox is mine and mine alone. Get your own,you filthy scrounger!Attempting to set headers after the document has started results inthis warning:
Warning: Cannot add header information - headers already sent
7.5.1. Different Content Types
TheContent-Type header identifies the type of document being returned.Ordinarily this is "text/html", indicating an HTMLdocument, but there are other useful document types. For example,"text/plain" forces the browser to treat the pageas plain text. This type is like an automatic "viewsource," and it is useful when debugging.In Chapter 9 and Chapter 10, we"ll make heavy use of theContent-Type header as we generate documents that are really graphicimages and Adobe PDF files.
7.5.2. Redirections
To send the browser to a new URL, known as aredirection , you set the Location header:
If you provide a partial URL (e.g.,"/elsewhere.html"), the redirectionis handled internally by the web server. This is only rarely useful,as the browser generally won"t learn that itisn"t getting the page it requested. If there arerelative URLs in the new document, the browser will interpret them asbeing relative to the document it requested, not the document it wassent. In general, you"ll want to redirect to anabsolute URL.
Xem thêm: Cách Tạo Router Đơn Giản Trong Php Giống Với Framework Mô Hình Mvc
7.5.3. Expiration
A server canexplicitly inform the browser, and any proxy caches that might bebetween the server and browser, of a specific date and time for thedocument to expire. Proxy and browser caches can hold the documentuntil that time or expire it earlier. Repeated reloads of a cacheddocument do not contact the server. However, an attempt to fetch anexpired document does contact the server.
To set the expiration time of a document, use the Expires header:
header("Expires: Fri, 18 Jan 2002 05:30:00 GMT");To expire a document three hours from the time the page wasgenerated, use time( ) and gmstrftime() to generate the expiration date string:
$now = time( );$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 60*60*3);header("Expires: $then");To indicate that a document "never"expires, use the time a year from now:
$now = time( );$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT", $now + 365*86440);header("Expires: $then");To mark a document as already expired, use the current time or a timein the past:
$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT");header("Expires: $then");This is the best way to prevent a browser or proxy cache from storingyour document:
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");For more information on controlling the behavior of browser and webcaches, see Chapter 6 of Web Caching, by DuaneWessels (O"Reilly).
7.5.4. Authentication
HTTPauthentication works through request headers and response statuses. Abrowser can send a username and password (thecredentials)in the request headers. If the credentials aren"tsent or aren"t satsifactory, the server sends a"401 Unauthorized" response andidentifies the realm of authentication (astring such as "Mary"sPictures" or "Your ShoppingCart") via the WWW-Authenticate header. This typicallypops up an "Enter username and password for..." dialog box on the browser, and the page is thenre-requested with the updated credentials in the header.
To handle authentication in PHP, check the username and password (thePHP_AUTH_USER and PHP_AUTH_PWelements of $_SERVER) and call header() to set the realm and send a "401Unauthorized" response:
header("WWW-Authenticate: Basic realm="Top Secret Files"");header("HTTP/1.0 401 Unauthorized");You can do anything you want to authenticate the username andpassword; for example, you could consult a database, read a file ofvalid users, or consult a Microsoft domain server. This examplechecks to make sure that the password is the username, reversed:
$auth_ok = 0;$user = $_SERVER<"PHP_AUTH_USER">;$pass = $_SERVER<"PHP_AUTH_PW">;if (isset($user) && isset($pass) && $user === strrev($pass)) { $auth_ok = 1;}if (!$auth_ok) { header("WWW-Authenticate: Basic realm="Top Secret Files""); header("HTTP/1.0 401 Unauthorized");}Putting this into a document gives something like:
}If you"re protecting more than one page, put theabove code into a separate file and include it atthe top of every protected page.
![]() | ||
7.4. Processing Forms | ![]() | 7.6. Maintaining State |
