05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Example 13-5. Log-rolling error handler<br />

function log_roller($error, $error_string) {<br />

$file = '/var/log/php_errors.log';<br />

if(filesize($file) > 1024) {<br />

rename($file, $file . (string) time( ));<br />

clearstatcache( );<br />

}<br />

error_log($error_string, 3, $file);<br />

}<br />

set_error_handler('log_roller');<br />

for($i = 0; $i < 5000; $i++) {<br />

trigger_error(time( ) . ": Just an error, ma'am.\n");<br />

}<br />

restore_error_handler( );<br />

Generally, while you are working on a site, you will want errors shown directly in the<br />

pages in which they occur. However, once the site goes live, it doesn’t make much<br />

sense to show internal error messages to visitors. A common approach is to use<br />

something like this in your php.ini file once your site goes live:<br />

display_errors = Off<br />

log_errors = On<br />

error_log = /tmp/errors.log<br />

This tells <strong>PHP</strong> to never show any errors, but instead to log them to the location specified<br />

by the error_log directive.<br />

Output buffering in error handlers<br />

Using a combination of output buffering and an error handler, you can send different<br />

content to the user, depending on whether various error conditions occur. For<br />

example, if a script needs to connect to a database, you can suppress output of the<br />

page until the script successfully connects to the database.<br />

Example 13-6 shows the use of output buffering to delay output of a page until it has<br />

been generated successfully.<br />

Example 13-6. Output buffering to handle errors<br />

<br />

Results!<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!