output buffers control and http headers

21
Output Buffers Control and HTTP Headers Nikolay Kostov Telerik Corporation www.telerik. com

Upload: jake

Post on 21-Feb-2016

48 views

Category:

Documents


0 download

DESCRIPTION

Output Buffers Control and HTTP Headers. Nikolay Kostov. Telerik Corporation. www.telerik.com. Contents. HTTP headers Output buffer control Browser cache Redirecting the browser. HTTP Headers. Each HTTP request and response contains of headers and body - PowerPoint PPT Presentation

TRANSCRIPT

Output Buffers Control and HTTP Headers

Output Buffers Controland HTTP HeadersNikolay KostovTelerik Corporationwww.telerik.comContentsHTTP headersOutput buffer controlBrowser cacheRedirecting the browserHTTP HeadersEach HTTP request and response contains of headers and bodyHeaders describe the transferred dataTypeLengthEncodingEtc.PHP can modify the response headersheader functionHTTP Headers (2)header($header, $replace, $response_code)Adds or modifies HTTP header of the response$header is string in the following formName: Value$replace sets whether to replace existing similar header with the same name or add it$response_code sets the HTTP response code (e.g. 302, 404, etc.)HTTP Headers ExampleRedirect the Web browser

Set multiple headers with one nameExample: force browser to require HTTP authentication

Example: page inaccessibleheader ("Location: http://otherplace.net");header ("WWW-Authenticate: Negotiate");header ('WWW-Authenticate: Basic realm="Secure Area"', false);header ("HTTP/1.0 404 Not Found");// or maybeheader ("HTTP/1.1 403 Forbidden");HTTP Headers ExampleExample: Page receives get parameter "down" that is some MP3 file ID in directory (MP3DIR constant)This script will either send 404 error on request or will return the MP3 file for download$file = MP3DIR.$_GET['down'].".mp3";if (!file_exists($file)) header ("HTTP/1.0 404 Not Found",true,404);else { header ('Content-Type: audio/x-mp3'); header ('Content-Length: '. filesize($file)); header('Content-Disposition: attachment; '. 'filename='.$_GET['down'].'.mp3'); echo file_get_contents($file);}Control Browser CacheBrowser cache resources, downloaded over networkOn next request they use the headers to detect if they should re-download or reuse the cached resourceResources carry set of headers to control the browser cachingExpires header, Last-Modified, If-Modified-Since headerETag, If-None-MatchCache-ControlControl Browser CacheHTTP Request Example:

HTTP Response Example:GET /index.html HTTP/1.0User-Agent: Mozilla/5.0From: something.somewhere.netAccept: text/html,text/plain,application/* Host: www.example.comIf-Modified-Since: Wed, 19 Oct 2005 10:50:00 GMT HTTP/1.1 304 Not ModifiedDate: Fri, 31 Dec 1999 23:59:59 GMT Modification DateServer sends Last-Modified and Expires dates in response for the resourceTells the browser how long the resource should be kept as current versionBoth in GMT formatBrowser sends If-Modified-Since header on each request with the date of the resource it has cachedIf version is latest, server replies with "303 Not Modified" HTTP codeETag approachETag is unique identifier for the resource and its versionSent by the server, stored by the browserBrowser sends on next request the ETag of the cached versionSends the ETag in If-None-Match headerNewer approachMost web servers send both Last-Modified and ETag headersControlling browser cache engineServer can send Cache-Control header that instruct the browser cache engineValue consists of comma separated name=value pairs or only namesmax-age=seconds sets maximum time that version should be considered freshs-maxage=seconds same as max-age but applies to proxiespublic marks headers of response as cacheableControlling browser cache engineno-cache instructs revalidation to be required on next requestUsually performed as HEAD requestno-store instructs not to store version of the resource under any circumstancesmust-revalidate tells cache engines they must obey and freshness information you give themSome caches load older version under some circumstancesproxy-revalidate similar to must-revalidate but applies to proxiesDisable Browser Cache - Exampleheader('Cache-Control: no-cache');header('Pragma: no-cache');header("Expires: 0"); Output modelThe Web server (Apache) buffers the script outputSends it automatically if there is enough data to send (buffer is full)Buffer can be controlledMultiple buffers can be defined and flushed, canceled or storedAllows reordering of the output dataExample first run script that generates page body, then print headExample first print output, then send headersOutput bufferFunctions for buffer control are prefixed with ob_ in PHPob_start ($callback, $chunk, $erase) starts new bufferAfter this function is called no output is sent to the browser, except headersOutput buffers are stackableCan call second ob_start while another is activeob_startAll parameters are optional$callback is function name to call when buffer is flushedThis function can modify the data to be sentReceives one parameter the data in the bufferMust return string the data to be sentIf $chunk is specified, buffer will flush if stored data reaches this sizeValue of 0 means no automatic flushValue of 1 sets $chunk to 4096 $erase sets whether the buffer should not be deleted until script endsFlushing the bufferob_flush sends the buffer content and erases all stored dataKeeps the buffer activeob_end_flush similar to ob_flush but destroys the bufferob_implicit_flush ($mode) sets implicit flush on or off$mode is optional boolean, defaults to trueWith implicit flush, all writing to the buffer is automatically sentReading the buffer dataob_get_contents returns the content of the current buffer as stringDoesn't clear or stop the bufferob_get_clean returns the buffer content and deletes itob_get_flush returns the buffer content, flushes it and deletes itDestroying bufferob_clean erases the data in the output buffer but does not delete the bufferob_end_clean cleans the output buffer data and deletes the bufferob_end_flush flushes the output buffer and deletes itOutput Buffers ControlQuestions???????????http://academy.telerik.comExercisesCreate pages login.php and main.php and implement the following logic:The login.php displays login form (username/password)If successfully authenticated, the user is redirected to the main.phpOtherwise an error message is shown and the login form is displayed againIf main.php is requested and the user is not logged in, it redirects to login.phpImplement also Logout functionality