I am writing a PHP class for generation of HTML output. For security reasons, I need to ensure that no code has sent output before this class does. Here are the two options I thought of:
Option 1: As an assertion
if( !$this->headersSent ) {
assert( '!headers_sent()' );
$this->headersSent = true;
// ...
}
Option 2: Using an if statement and die()
if( !$this->headersSent ) {
if( headers_sent() ) {
die( 'For security, refusing to continue: headers already sent.' );
}
$this->headersSent = true;
// ...
}
Wikipedia says, “Assertions should be used to document logically impossible situations and discover programming errors.”
- This class is part of a specific application, and I consider it a programming error to send HTML output without using this class. So
assert()should be used. - On the other hand, this application might become open source one day, and someone might customize it. He might have assertions switched off, and so the resulting security problem might go unnoticed. So
die()should be used.
Which one is better practice?
You would probably want to throw an Exception there.
http://php.net/manual/en/language.exceptions.php