Monday 3 September 2018

The ldap_connect () function in php accepts any value and does not start 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 f.i 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.

0 comments:

Post a Comment