xotix
xotix

Reputation: 520

Check if a server is online

I'm currently implementing LDAP Authentication. I cache the credentials as a fallback in case the LDAP server is offline. As part of this caching I need to check if my LDAP server is online. Rather than using PHP's Ldap methods it would be better to use something simple like a ping.

Please note that it should be able to handle any protocols. E.g., I can't use fsockopen because it does not support ldaps://. [I know that I could register my own protocol wrappers].

I want this check to be generic and simple.

Upvotes: 0

Views: 700

Answers (1)

heiglandreas
heiglandreas

Reputation: 3861

I'm using fsockopen for exactly that purpose. It doesn't matter whether it supports ldaps or not I figured out, because there are two possibilities in the end:

  • The appropriate port is open, so I can assume that the LDAP-Server is up and running or
  • The appropriate port is not open, so I can assume that the LDAP-Server is not running.

You can check that like this:

$fp = @fsockopen($host, $port, $errno, $errstr, 30);
if (! $fp) {
    // Port is unavailable
}
fclose($fp);

Now you know, the port to connect to is open and I can fire up LDAP.

I've found two edge-cases that you won't be able to check for using this method though

  • The LDAP-Server is in an undefined state and has the port still open but is not responding or
  • Some other application has opened the port.

You can check that though by using

$con = ldap_connect($ldapURI);
if (! ldap_bind($con, $user, $password)) {
    // Something is fishy
}

Fishy might be invalid credentials (which should not happen at this first bind, right?) or the server listening on that port is not responding in a manner that we expect. So it's either not an LDAP-Server or the server is in an undefined state.

To fail fast, you should adapt the timeouts appropriately so you're not waiting half a minute just to know that something went wrong.

YOu can set the timeout for fsockopen using the fifth parameter and you can set the timeouts for LDAP using

ldap_set_option($con, LDAP_OPT_NETWORK_TIMEOUT, [whatever is appropriate]);
ldap_set_option($con, LDAP_OPT_TIMEOUT, [whatever is appropriate]);
ldap_set_option($con, LDAP_OPT_TIMELIMIT, [whatever is appropriate]);
// Only available when your LDAP-extension is compiled against the Netscape LDAP C-SDK
ldap_set_option($con, LDAP_X_OPT_CONNECT_TIMEOUT, [whatever is appropriate]);

You'll need to set them after ldap_connect but before ldap_bind.

LDAP_OPT_TIMEOUT and LDAP_X_OPT_CONNECT_TIMEOUT are not (yet) documented on php.net though!

For more infos on these constants have a look at https://linux.die.net/man/3/ldap_set_option but beware that not all the constants mentioned there are implemented in the PHP-LDAP-Extension.

Upvotes: 1

Related Questions