在 PHP 中检查 headers_sent() 时断言或退出/死亡?
我正在编写一个 PHP 类来生成 HTML 输出。出于安全原因,我需要确保在此类之前没有代码发送输出。以下是我想到的两个选项:
选项 1:作为断言
if( !$this->headersSent ) {
assert( '!headers_sent()' );
$this->headersSent = true;
// ...
}
选项 2:使用 if
语句和 die()
if( !$this->headersSent ) {
if( headers_sent() ) {
die( 'For security, refusing to continue: headers already sent.' );
}
$this->headersSent = true;
// ...
}
维基百科说,“断言应该用于记录逻辑上不可能的情况并发现编程错误。”
- 此类是特定应用程序的一部分,我认为在不使用此类的情况下发送 HTML 输出是一个编程错误。所以应该使用assert()。
- 另一方面,这个应用程序有一天可能会开源,有人可能会对其进行定制。他可能关闭了断言,因此由此产生的安全问题可能不会被注意到。所以应该使用
die()
。
哪一种练习更好?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想在那里抛出异常。
http://php.net/manual/en/language.exceptions.php
You would probably want to throw an Exception there.
http://php.net/manual/en/language.exceptions.php