What are some best practices for handling LDAP connection errors in PHP?

When handling LDAP connection errors in PHP, it is important to implement error handling to gracefully handle any potential issues that may arise. This can include catching exceptions, logging errors, and providing appropriate error messages to the user.

try {
    $ldapconn = ldap_connect("ldap.example.com");
    if (!$ldapconn) {
        throw new Exception("Unable to connect to LDAP server");
    }
    
    // Bind to LDAP server
    $ldapbind = ldap_bind($ldapconn, "cn=admin,dc=example,dc=com", "password");
    if (!$ldapbind) {
        throw new Exception("Unable to bind to LDAP server");
    }
    
    // Perform LDAP operations
    
    ldap_close($ldapconn);
} catch (Exception $e) {
    error_log("LDAP Error: " . $e->getMessage());
    echo "An error occurred while connecting to LDAP server. Please try again later.";
}