我正在为我的 php 应用程序实现一个 ajax 文件上传(使用 CodeIgniter)。
我根据 http://andrewcurioso.com/2010/06/detecting-file-size-overflow-in-php/ 检测上传的 POST 数据是否过大 (>post_max_size)并尝试发送适当的 JSON 编码错误响应。
但是输出中包含的相应 php 警告完全破坏了我的 JSON 响应!
<br />
<b>Warning</b>: POST Content-Length of 105906405 bytes exceeds the limit of 8388608 bytes in <b>Unknown</b> on line <b>0</b><br />
[{"error":"Posted data is too large. 105906405 bytes exceeds the maximum size of 8388608 bytes."}]
我不想在客户端解析和过滤警告,这看起来很难看。 并且在全局范围内禁用所有 php 警告似乎是不合适的。
我可以在 php 函数的上下文中禁用特定的 PHP 警告吗?或者将其包装在有效的 json 响应中?
最佳答案
在生产服务器上:始终禁用 php 警告。
在开发机器上: 出于测试目的禁用该页面的所有警告,并在测试完成并确认功能正常工作后重新启用。
提示:我更喜欢全局设置一个变量,并根据该变量启用或禁用所有 php 和数据库警告通知。例如,如果您使用 apache,您可以在 .htaccess
中设置它。
我在 .htaccess
中有这个:
- 生产:
SetEnv DEVELOPMENT Off
- 开发:
SetEnv DEVELOPMENT On
在 php 代码中:
if( strtolower(getenv('DEVELOPMENT')) == "on" ) {
ini_set("display_errors",2);
ini_set('error_reporting', E_ALL | E_STRICT);
}
禁用 .htaccess 使用的所有错误
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
如果你想变得非常棘手,你可以添加如下检查:
if(error_get_last() !== null)
并设置一个 http header 并从 javascript 检查 json 输出和加载页面时查看错误日志或在屏幕上显示错误,如果你愿意的话,我仍然强烈建议你禁用错误在生产环境中显示代码。
有关此的更深入讨论,请查看 this article .
关于PHP 警告破坏 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12872515/