+ All Categories
Home > Documents > Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Date post: 28-Mar-2015
Category:
Upload: malia-wilds
View: 214 times
Download: 0 times
Share this document with a friend
Popular Tags:
32
Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation
Transcript
Page 1: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Output Buffering Controlwith php

By Tim LeClairSenior Web Developer, Skills Gatekey Corporation

Page 2: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Who is this presentation for?• Web Developers / Programmers

Output buffering is a unique tool that allows for creative ways to make things happen and provide more options.

• Web Designers IT Project managersWeb Designers, It Managers, in creating better websites, understanding an overview of the powers that web technologies provide will allow you to create to your fullest extent.

• Owners of websites that push / plan to push the limitsBefore you expand hardware wise, it is important to tweak your website’s efficiency prior or your cost and complexity will multiply quickly.

• Knowledge to help Intelligence create something new

Page 3: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Why use Output Buffers?

• More control

• More speed

• Less bandwidth

• Less Database connections

• Reduce redundant script execution

• Put your html in a file or variable

• Tune / manipulate your output

Lesson objectives

Gains in one can equal loss in another!

Page 4: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Output Control Functions

• ob_start(callback function) Turn on output buffering

Initialize / Functions / Exiting

•output_add_rewrite_var Will also turn on the output buffer

Page 5: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Output Control Functions•ob_end_clean Clean (erase) the output buffer and turn off output buffering

•ob_end_flush Flush (send) the output buffer and turn off output buffering

•ob_get_clean Get current buffer contents and delete current output buffer

•ob_get_flush Flush the output buffer, return it as a string and turn off output buffering

Initialize / Functions / Exiting

Page 6: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Output Control FunctionsInitialize / Functions / Exiting

• ob_flush Flush (send) the output buffer

• ob_clean Clean (erase) the output buffer

• ob_get_contents Return the contents of the output buffer

• ob_implicit_flush Turn implicit flush on/off

• flush Flush the output buffer

Page 7: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Output Control FunctionsInitialize / Functions / Exiting

• ob_get_length Return the length of the output buffer

• ob_get_level Return the nesting level of the output buffering mechanism

• ob_get_status Get status of output buffers

• ob_list_handlers List all output handlers in use

• output_add_rewrite_var Add URL rewriter values

• output_reset_rewrite_vars Reset URL rewriter values

• ob_iconv_handler() Convert character encoding as output buffer handler

• ob_tidyhandler() ob_start callback function to repair the buffer (requires libtidy installation)

Page 8: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Compression options

• Web server Levelmod_deflate (apache 2)mod_gzip

• Apache.conf• .htaccess

• Script level• Zlib.output.compression• Output buffer function gzhandler• Php.ini• Php script

Remember rule: compressing twice is a bad thing!

This is not a lesson on compression but need to know to prevent conflict.

Page 9: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Gzip and Output Buffers• ob_start(“ob_gzhandler”) requires the zlib extension.• You cannot use both ob_gzhandler and zlib.output compression.• Gzip + Gzip + unGzip = TRASH• Differences

http://www.php.net/manual/en/function.ob-gzhandler.php#30159

• Website tester for compression at:

http://www.seoconsultants.com/tools/compression.asp

Page 10: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Zlib extension• Zlib support in PHP is not enabled by default. You

will need to configure PHP

• The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.Note: Built-in support for zlib on Windows is available with PHP 4.3.0.

XAMPP for Linux

The distribution for Linux systems (tested for SuSE, RedHat, Mandrake and Debian) contains: Apache, MySQL, PHP & PEAR, Perl, ProFTPD, phpMyAdmin,

OpenSSL, GD, Freetype2, libjpeg, libpng, gdbm, zlib, expat, Sablotron, libxml, Ming, Webalizer, pdf class, ncurses, mod_perl, FreeTDS, gettext, mcrypt, mhash, eAccelerator, SQLite and IMAP C-Client.

XAMPP for Windows

The distribution for Windows 98, NT, 2000, 2003, XP and Vista. This version contains: Apache, MySQL, PHP + PEAR, Perl, mod_php, mod_perl, mod_ssl, OpenSSL, phpMyAdmin, Webalizer, Mercury Mail Transport System for Win32 and NetWare Systems v3.32, Ming, JpGraph, FileZilla FTP Server, mcrypt, eAccelerator, SQLite, and WEB-DAV + mod_auth_mysql.

phpinfo();

Page 11: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

HTTP compression• Most content is cached by the user’s browser. Dynamic content in the HTML code is not cacheable as it changes, so HTTP compression can lessen the bandwidth and time to 1/3 to 1/5 easily. That is a big savings!

Yslow On Firefox with Firebug

SmartSniff http://www.nirsoft.netWithout compression

Twitter

With compression

Page 12: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Using callback functions • <?php • ob_start("ob_gzhandler");• // rest of your code• ?>

Getting Started• <?php • ob_start() ;• // rest of your code• ?>

Page 13: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Exiting output buffersEasiest way

• Just let the script end !

Flush to lower buffer level and end current level<?php • // rest of your code• ob_end_flush();• ?>

Erase and end current buffer level• <?php • // rest of your code• ob_end_clean();• ?>

Almost as easy

• <?php • // rest of your code• $ob = ob_get_flush();• ?>

• <?php • // rest of your code• $ob = ob_get_clean();• ?>

Page 14: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Buffer Levels

Level 1

Level 2

Level 3

Level 4

Server

Level 3

Output to Browser

Ob_start(ob_gzhandler)

Ob_start(condense)

Ob_start(ob_tidyhandler)

Ob_start20 Db calls

cache.php

If(cache.php )readfile(cache.php)

else Level 4

Tidy it up

Remove junk

Compression

Ob_start(4heckofit)

Header

Top

Right MenuAdvertisement

LeftAds

BLOG

Header Top Right MenuAdvertisement

BLOG LeftAds Bottom

Bottom

Page 15: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 1a - Output buffering

<?php// top of index.phpob_start();// the rest of your websiteob_end_flush();?>

Page 16: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 2a – Nesting

1452Answer =

<?phpob_start(); echo "1";

ob_start(); echo "2"; $s1 = ob_get_contents();

ob_start(); echo "3"; $s2 = ob_get_contents();

ob_end_flush();ob_end_clean();

echo "4";ob_start();

echo "5";ob_end_flush();

echo $s1;ob_end_flush();?>

Page 17: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 2b – Nesting

12452Answer =

<?phpob_start(); echo "1";

ob_start(); echo "2"; $s1 = ob_get_contents(); ob_flush();

ob_start(); echo "3"; $s2 = ob_get_contents();

ob_end_flush();ob_end_clean();

echo "4";ob_start();

echo "5";ob_end_flush();

echo $s1;ob_end_flush();?>

Page 18: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 2c – Nesting

1234523Answer =

<?phpob_start(); echo "1";

ob_start();echo "2";$s1 = ob_get_contents();ob_flush();ob_start();

echo "3";$s2 = ob_get_contents();ob_flush();

ob_end_flush();ob_flush();

ob_end_clean(); echo "4";

ob_start();echo "5";

ob_end_flush(); echo $s1.$s2; ob_flush(); echo "7";ob_end_clean();?>

Page 19: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 3a – Other functions<?phpob_start();ob_start();echo ob_get_length().'- length<br>';echo ob_get_level().'- level<br>';echo ob_get_length().'- length<br>';ob_end_flush();echo ob_get_level().'- level<br>';ob_end_flush();?>

0- length2- level25- length1- level

Level 0 = no buffer

Page 20: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 3b – Other functions<?phpob_start();ob_start(“ob_tidyhandler”);echo '<br>';echo '<br>';

$s = ob_get_status(true);print_r($s);ob_end_flush();ob_end_flush();?>Array (

[0] => Array ( [chunk_size] => 0 [size] => 40960 [block_size] => 10240 [type] => 1 [status] => 0 [name] => default output handler [del] => 1 )

[1] => Array ( [chunk_size] => 0 [size] => 40960 [block_size] => 10240 [type] => 1 [status] => 0 [name] => ob_tidyhandler output handler [del] => 1 ) )

Page 21: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 3c – Other functions<?phpob_start("ob_gzhandler");

ob_start(“condense”);ob_start('ob_tidyhandler');

ob_start();

$s = ob_list_handlers();print_r($s);

ob_end_flush();ob_end_flush();

ob_end_flush();ob_end_flush();?>

Array ( [0] => ob_gzhandler [1] => ob_tidyhandler [2] => default output handler )

Page 22: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 4a – Output to file<?php ob_start("ob_gzhandler");// dynamic content// check database if page has been modified$cachefile = $_SERVER['DOCUMENT_ROOT']."/cache/cache09.php";if($pagemodified != 'Y' && file_exists($cachefile)){ readfile($cachefile);}else{// content to be cached$fp = fopen($cachefile, 'w');fwrite($fp, ob_get_contents());@chmod($fp,0755);}// more dynamic contentob_end_flush()?>

Page 23: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 4b – Cache file system<?php$cacheFile = 'cache.html';

if ( (file_exists($cacheFile)) && ((fileatime($cacheFile) + 600) > time()) ){ $content = file_get_contents($cacheFile); echo $content;} else { ob_start(); // write content echo 'What Ever You Want!'; $content = ob_get_clean(); file_put_contents($cacheFile,$content); echo $content;}?>

Page 24: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 5 – rewrite variable<?phpoutput_add_rewrite_var('var', 'value');echo '<a href="file.php">link</a><a href="http://example.com">link2</a>';echo '<form action="script.php" method="post"><input type="text" name="var2" /></form><br>';print_r(ob_list_handlers());ob_end_flush();output_reset_rewrite_vars();echo '<br><a href="file.php">link</a><a href="http://example.com">link2</a>';echo '<form action="script.php" method="post"><input type="text" name="var2" /></form><br>';print_r(ob_list_handlers());?><a href="file.php?var=value">link</a><a href="http://example.com">link2</a><form action="script.php" method="post"><input type="hidden" name="var" value="value" />

Page 25: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 6 – Less HTML less readable<?phpfunction condense($buffer){// change new lines and tabs to single spaces$buffer = str_replace(array("\r\n", "\r", "\n", "\t"), ' ',$buffer);// multispaces to single...$buffer = ereg_replace(" {2,}", ' ',$buffer);// remove single spaces between tags$buffer = str_replace("> <", "><", $buffer);// remove single spaces around &nbsp;$buffer = str_replace(" &nbsp;", "&nbsp;", $buffer);$buffer = str_replace("&nbsp; ", "&nbsp;", $buffer);return $buffer;}ob_start(" condense ");// your websiteob_end_flush();?>

Page 26: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 7 – Tidyhandler

<?phpob_start('ob_tidyhandler');echo '<p>test</i>';?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"><html><head><title></title></head><body><p>test</p></body></html>

http://ditio.net/2008/01/03/is-your-html-code-tidy/

Uncomment in php.ini 4 xampp;extension=php_sybase_ct.dll;extension=php_threads.dllextension=php_tidy.dll;extension=php_timezonedb.dll;extension=php_translit.dll

Page 27: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Project 8 – Compression level<?phpini_set('zlib.output_compression_level', 8); ob_start("ob_gzhandler");// htmlob_end_flush();?>

Page 28: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Bug reports

• http://bugs.php.net/

• Search terms like “ob_start”

• Output buffers can effect the whole document, so it is wise to test all aspects of your website for functionality and with various browsers.

Page 29: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

WIMP issues

• Example:

ORIGINAL <add name="php" path="*.php" verb="*" modules="IsapiModule" scriptProcessor="C:\Program Files\PHP\php5isapi.dll" resourceType="Unspecified"  />

CHANGE <add name="php" path="*.php" verb="*" modules="IsapiModule" scriptProcessor="C:\Program Files\PHP\php5isapi.dll" resourceType="Unspecified" responseBufferLimit="0" />

You MUST add responseBufferLimit="0“ By default, IIS buffers everything up to a massive 4MB

This lecture was written with Apache as the example server. If you are using IIS then it is recommended to look closely at how IIS handles buffers and compression.

Page 30: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Summary

• More control

• More speed

• Less bandwidth

• Less MySQL connections

• Reduce redundant script execution

• Put your html in a file or variable

• Tune your output

Did lesson meet its intended objectives

Page 31: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

Questions

Sorry, we do not answer questions If you come across this document online, please refer to www.php.net or use a search engine to find your answers. Else if you catch me standing in front of you, then I will do my best to answer your questions.

Page 32: Output Buffering Control with php By Tim LeClair Senior Web Developer, Skills Gatekey Corporation.

The End• Acknowledgments:• Rasmus Lerdorf creator of PHP• Mehdi Achour, Friedhelm Betz, Antony Dovgal, Nuno Lopes,

Hannes Magnusson, Georg Richter, Damien Seguy and Jakub

Vrana noted active contributors of PHP


Recommended