12. output buffers control - php & mysql web development

22
Output Buffers Control and HTTP Headers Output Buffers, HTTP Headers Nikolay Kostov Telerik Software Academy academy.telerik.com Technical Trainer http://nikolay.it emy.telerik.com/.../ php -school- academy-meeting

Upload: telerik-software-academy

Post on 18-May-2015

6.472 views

Category:

Education


0 download

DESCRIPTION

Basic concepts about Output Buffers Control and HTTP Headers Telerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2011/10/11/php-school-academy-meeting The website and all video materials are in Bulgarian. This lecture discusses the following topics: HTTP headers Output buffer control Browser cache Redirecting the browser

TRANSCRIPT

Page 2: 12. Output Buffers Control - PHP & MySQL Web Development

Contents HTTP headers Output buffer control Browser cache Redirecting the browser

Page 3: 12. Output Buffers Control - PHP & MySQL Web Development

HTTP Headers Each HTTP request and response contains of headers and body Headers describe the transferred

data Type

Length

Encoding

Etc.

PHP can modify the response headers header function

Page 4: 12. Output Buffers Control - PHP & MySQL Web Development

HTTP Headers (2) header($header, $replace, $response_code) Adds or modifies HTTP header of the

response

$header is string in the following form

Name: 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.)

Page 5: 12. Output Buffers Control - PHP & MySQL Web Development

HTTP Headers – Example

Redirect the Web browser

Set multiple headers with one name Example: force browser to require

HTTP authentication

Example: page inaccessible

header ("Location: http://otherplace.net");header ("Location: http://otherplace.net");

header ("WWW-Authenticate: Negotiate");header ('WWW-Authenticate: Basic realm="Secure Area"', false);

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");

header ("HTTP/1.0 404 Not Found");// or maybeheader ("HTTP/1.1 403 Forbidden");

Page 6: 12. Output Buffers Control - PHP & MySQL Web Development

HTTP Headers – Example

Example: 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);}

$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);}

Page 7: 12. Output Buffers Control - PHP & MySQL Web Development

Control Browser Cache Browser cache resources, downloaded over network On next request they use the

headers to detect if they should re-download or reuse the cached resource

Resources carry set of headers to control the browser caching Expires header, Last-Modified, If-Modified-Since header

ETag, If-None-Match

Cache-Control

Page 8: 12. Output Buffers Control - PHP & MySQL Web Development

Control Browser Cache

HTTP 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

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 HTTP/1.1 304 Not ModifiedDate: Fri, 31 Dec 1999 23:59:59 GMT

Page 9: 12. Output Buffers Control - PHP & MySQL Web Development

Modification Date Server sends Last-Modified and Expires dates in response for the resource Tells the browser how long the

resource should be kept as current version

Both in GMT format

Browser sends If-Modified-Since header on each request with the date of the resource it has cached If version is latest, server replies

with "303 Not Modified" HTTP code

Page 10: 12. Output Buffers Control - PHP & MySQL Web Development

ETag approach ETag is unique identifier for the resource and its version Sent by the server, stored by the

browser

Browser sends on next request the ETag of the cached version Sends the ETag in If-None-Match

header

Newer approach

Most web servers send both Last-Modified and ETag headers

Page 11: 12. Output Buffers Control - PHP & MySQL Web Development

Controlling browser cache engine

Server can send Cache-Control header that instruct the browser cache engine Value consists of comma separated

name=value pairs or only names max-age=seconds – sets maximum

time that version should be considered fresh

s-maxage=seconds – same as max-age but applies to proxies

public – marks headers of response as cacheable

Page 12: 12. Output Buffers Control - PHP & MySQL Web Development

Controlling browser cache engine

no-cache – instructs revalidation to be required on next request

Usually performed as HEAD request

no-store – instructs not to store version of the resource under any circumstances

must-revalidate – tells cache engines they must obey and freshness information you give them

Some caches load older version under some circumstances

proxy-revalidate – similar to must-revalidate but applies to proxies

Page 13: 12. Output Buffers Control - PHP & MySQL Web Development

Disable Browser Cache - Example

header('Cache-Control: no-cache');header('Pragma: no-cache');header("Expires: 0");

header('Cache-Control: no-cache');header('Pragma: no-cache');header("Expires: 0");

Page 14: 12. Output Buffers Control - PHP & MySQL Web Development

Output model The Web server (Apache) buffers the

script output

Sends it automatically if there is enough data to send (buffer is full)

Buffer can be controlled

Multiple buffers can be defined and flushed, canceled or stored

Allows reordering of the output data

Example – first run script that generates

page body, then print head

Example – first print output, then send

headers

Page 15: 12. Output Buffers Control - PHP & MySQL Web Development

Output buffer Functions for buffer control are prefixed with ob_ in PHP

ob_start ($callback, $chunk, $erase) – starts new buffer After this function is called no output is sent to the browser, except headers

Output buffers are stackable Can call second ob_start while

another is active

Page 16: 12. Output Buffers Control - PHP & MySQL Web Development

ob_start All parameters are optional

$callback is function name to call when buffer is flushed This function can modify the data to be

sent

Receives one parameter – the data in the buffer

Must return string – the data to be sent If $chunk is specified, buffer will flush

if stored data reaches this size Value of 0 means no automatic flush Value of 1 sets $chunk to 4096

$erase sets whether the buffer should not be deleted until script ends

Page 17: 12. Output Buffers Control - PHP & MySQL Web Development

Flushing the buffer ob_flush – sends the buffer content and

erases all stored data

Keeps the buffer active ob_end_flush – similar to ob_flush but

destroys the buffer ob_implicit_flush ($mode) – sets

implicit flush on or off

$mode is optional boolean, defaults to true

With implicit flush, all writing to the buffer is automatically sent

Page 18: 12. Output Buffers Control - PHP & MySQL Web Development

Reading the buffer data ob_get_contents – returns the content of the current buffer as string Doesn't clear or stop the buffer

ob_get_clean – returns the buffer content and deletes it

ob_get_flush – returns the buffer content, flushes it and deletes it

Page 19: 12. Output Buffers Control - PHP & MySQL Web Development

Destroying buffer ob_clean – erases the data in the output buffer but does not delete the buffer

ob_end_clean – cleans the output buffer data and deletes the buffer

ob_end_flush – flushes the output buffer and deletes it

Page 20: 12. Output Buffers Control - PHP & MySQL Web Development

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Output Buffers Control and HTTP

Headers

http://academy.telerik.com

Page 21: 12. Output Buffers Control - PHP & MySQL Web Development

Exercises1. Create 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.php

Otherwise an error message is shown and the login form is displayed again

If main.php is requested and the user is not logged in, it redirects to login.php

Implement also “Logout” functionality