PHP:死掉还是检查结果?
我正在使用 PHP 实现 LDAP,我必须说这相当容易。但是,我对使用 die() 或检查函数返回有疑问。从下面的代码(取自此处),什么是如果将 die()
与 ldap_connect
一起使用,检查 $ldapconn
的要点是什么?如果 ldap_connect
出现问题,PHP 不是应该以 die()
退出吗?
// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
or die("Could not connect to LDAP server.");
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}
}
I am implementing LDAP with PHP which is going fairly easily I must say. However I have a question regarding the use of die()
or checking function returns. From the below code (taken from here), what is the point of checking for $ldapconn
if you use die()
with the ldap_connect
? Isn't PHP supposed to exit with die()
if something goes wrong with ldap_connect
anyway?
// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
or die("Could not connect to LDAP server.");
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它没有任何目的。如果 ldap_connect 失败,则会返回 false,从而死亡,因此您可以删除 2 个死亡之一。
我建议删除该死亡并添加一些良好的错误处理。
来源: PHP ldap_connect
在 PHP5.3 中测试 ldap_connect 时应该小心我可以成功连接到 ldap_connect 始终返回 true 的任何服务器(现有或不存在)。链接类型始终为 ldap_connection,但实际上可能无法工作/成功。我建议使用 @ldap_bind 验证连接是否有效,然后检查是否有错误。
It doesn't serve any purpose. ldap_connect will return false if it fails thus die, so you can delete one of the 2.
I would suggest to delete the die and add some good error handling.
Source: PHP ldap_connect
You should be careful with testing ldap_connect in PHP5.3 I can successfully connect to any server ( existing or not ) where ldap_connect always returns true. The link type is always ldap_connection but may not actually work / be successful. I'd suggest verifying the connection is valid with @ldap_bind then check for errors.
你说得对,这确实是多余的。
顺便说一句,您应该只在模型原型或非常简单的 CLI 脚本中
die
。对于“真正的”网站,您应该更优雅地处理错误并输出正确的错误页面,而不是仅仅死
。You're right, that's pretty redundant.
As an aside, you should only ever
die
in mockup prototypes or really simple CLI scripts. For "real" websites, you should handle errors more gracefully and output proper error pages instead of justdie
ing.如果连接失败,ldap_connect() 返回 false。在这种情况下,脚本会被 die() 停止并返回一条消息。该行下面的其他代码不会被执行。
ldap_connect() returns false if the connection fails. In this case the script is stopped by die() and a message is returned. No other code below this line will be executed.
ldap_connect 出错时返回 false。模具在那里很有用,因为有了它,您将能够设置一个可读的错误/警告供开发人员查看。
ldap_connect returns false on error. The die is of good use over there because with it you will be able set a readable error/warning for the developer to see.