简体   繁体   中英

ldap_connect() function in php accepts any value and doesnt throw an error

I am writing a php code to connect to my LDAP server.

$adServer = $ini['ldap'];
$ldap = ldap_connect($adServer) or die("Could not connect to {$adServer}");

The Value for $adServer I am fetching from a configuration file.

Looks like ldap_connect() is not throwing an error when I pass blank value or any other random value like "Hello".

I tried giving the below code to check if any error message was generated.

echo ldap_error($ldap)

It always says 'Success'.

Hence I am not able to authenticate if the connection was established or not to the LDAP Server and throw an appropriate error message.

In what situation does the 'die' get triggered for ldap_connect() function. I would like to throw an appropriate error message to the end user if the Server Name provided in the configuration file is not working.

Note: I am using Version 5.6 for PHP

ldap_connect() always returns a resource when it can parse the provided parameter as a URL. The first time that resource is actually used (and therefore a connection is established and a possible failure can be detected) is when using ldap_bind() .

As ldap_connect() almost always returns a resource-handle (as described in http://php.net/ldap_connect ) your construct with die() wouldn't do what you want. It will only work if the provided parameter can't be parsed as URL internally. so as long as you provide a string that looks like a servername or a URL, everything works.

I always check after an unsuccessfull ldap_bind() what happened exactly and then throw an Exception depending on the error returned by . Alternatively I sometimes check before using the ldap_bind() by opening (and just closing) a connection using fi fsockopen() . If that connection can't be opened the ldap-connection won't work either.

The examples on the referred php-documentation are missleading and it seems we will have to change them. So thanks for spotting and throwing up the question!

BTW: calling @ldap_connect('ldap:'); for instance would be such a case where the die() would work as it's an incomplete URL. Or using a string with whitespace.

I found a better way to do authenticate instead of using die. After ldap connect, we would continue using ldap bind. If the bind fails, then we can check for the ldap error.

$ldap = @ldap_connect($adServer);
$bind = @ldap_bind ($ldap, $ldaprdn, $password);
if (!$bind) {  // If Bind Failed then.
    if (ldap_errno ($ldap) == 49 {
        //Invalid Credentials
    } else {
    //LDAP Connection to LDAP Server Failed
    }
}

For a list of all the LDAP Error Number, you can check here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM