开发者

PHP: die or check results?

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 ($l开发者_运维知识库dapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }

}


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.


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 just dieing.


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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜