How can LDAP connection errors be handled effectively in PHP scripts?

LDAP connection errors in PHP scripts can be handled effectively by using try-catch blocks to catch and handle exceptions that may occur during the LDAP connection process. This allows for graceful error handling and provides the opportunity to log or display specific error messages to aid in troubleshooting.

try {
    $ldapconn = ldap_connect("ldap://ldap.example.com");
    if (!$ldapconn) {
        throw new Exception("Failed to connect to LDAP server");
    }
    
    // LDAP bind, search, or other operations can be performed here
    
    ldap_close($ldapconn);
} catch (Exception $e) {
    echo "LDAP Connection Error: " . $e->getMessage();
}