In this second, and concluding, article, dig deeper into PHP'sLDAP API by writing complex search queries and building a Web-basedadministration module to retrieve and modify entries from the LDAP directorytree.
You might remember, from the scripts in this article, my copious use of the ldap_error() and ldap_errno() functions. As you must have guessed by now, these are built-in API functions to record and display error messages.
The ldap_errno() function returns a pre-defined error number for each LDAP error. While this number is, by itself, not very useful, it acquires significance when coupled with yet another PHP function, ldap_err2str(), which returns a user-friendly error message for display to the user.
In order to see how this function may be used, consider the next example, which uses the ldap_error() and ldap_err2str() functions to trap and generate the error message resulting from an attempt to bind to a non-existent LDAP server:
<html>
<head>
</head>
<body>
<?php
// specify the LDAP server to connect to
$conn = ldap_connect("www.somewhere.com") or die("Could not connect to
server");
// bind to the LDAP server specified above
$r = ldap_bind($conn);
// if not successful, display error message
if(!$r)
{
echo "An error occurred. Error number " . ldap_errno($conn) . ": " .
ldap_err2str(ldap_errno($conn)); }
// further processing as required
// all done? clean up
ldap_close($conn);
?>
</body>
</html>
Here's what the output looks like:
There's also a shortcut - the ldap_error() function, which returns the last error message generated. The following code snippet, which is equivalent to the one above, demonstrates:
<html>
<head>
</head>
<body>
<?php
// specify the LDAP server to connect to
$conn = ldap_connect("www.somewhere.com") or die("Could not connect to
server");;
// bind to the LDAP server specified above
$r = ldap_bind($conn);
// if not successful, display display error message
if(!$r)
{
echo "An error occurred - " . ldap_error($conn);
}
// further processing as required
// all done? clean up
ldap_close($conn);
?>
</body>
</html>