A Sample LDAP Application in PHP Page 16
February 22, 2002
This function encapsulates the connection to the LDAP server and
also the binding to the appropriate part of the DN tree:
function connectBindServer($bindRDN = 0, $bindPassword = 0)
{
global $ldapServer;
global $ldapServerPort;
$linkIdentifier = ldap_connect($ldapServer, $ldapServerPort);
if ($linkIdentifier) {
If no RDN and password is specified, we attempt an anonymous
bind, else we bind using the provided credentials:
if (!$bindRDN && !$bindPassword) {
if (!@ldap_bind($linkIdentifier)) {
displayErrMsg("Unable to bind to LDAP server ! !");
return 0;
}
} else {
if (!ldap_bind($linkIdentifier, $bindRDN, $bindPassword)) {
displayErrMsg("Unable to bind to LDAP server ! !");
return 0;
}
}
} else {
displayErrMsg("Unable to connect to the LDAP server! !");
return 0;
}
return $linkIdentifier;
}
[In the code above, there should be no space between the
double "!" marks. They have been separated for formatting
purposes.]
Given a search criteria string, this function creates a search
filter expression:
function createSearchFilter($searchCriteria)
{
$noOfFieldsSet = 0;
if ($searchCriteria["cn"]) {
$searchFilter = "(cn=*" . $searchCriteria["cn"] . "*)";
++$noOfFieldsSet;
}
if ($searchCriteria["sn"]) {
$searchFilter .= "(sn=*" . $searchCriteria["sn"] . "*)";
++$noOfFieldsSet;
}
if ($searchCriteria["mail"]) {
$searchFilter .= "(mail=*" . $searchCriteria["mail"] . "*)";
++$noOfFieldsSet;
}
if ($searchCriteria["employeenumber"]) {
$searchFilter .= "(employeenumber=*" .
$searchCriteria["employeenumber"] . "*)";
++$noOfFieldsSet;
}
if ($searchCriteria["ou"]) {
$searchFilter .= "(ou=*" . $searchCriteria["ou"] . "*)";
++$noOfFieldsSet;
}
if ($searchCriteria["telephonenumber"]) {
$searchFilter .= "(telephonenumber=*" .
$searchCriteria["telephonenumber"] . "*)";
++$noOfFieldsSet;
}
We perform a logical AND on all specified search criteria to
create the final search filter:
if ($noOfFieldsSet >= 2) {
$searchFilter = "(&" .$searchFilter. ")";
}
return $searchFilter;
}
This function given a link identifier obtained from the
connectBindServer() function and the search filter
created by createSearchFilter() performs a search on
the directory:
function searchDirectory($linkIdentifier, $searchFilter)
{
global $baseDN;
$searchResult = ldap_search($linkIdentifier, $baseDN, $searchFilter);
We count the search results to see if we got any entries at all:
if (ldap_count_entries($linkIdentifier, $searchResult) <= 0) {
displayErrMsg("No entries returned from the directory");
return 0;
} else {
$resultEntries = ldap_get_entries($linkIdentifier, $searchResult);
return $resultEntries;
}
}
A Sample LDAP Application in PHP Page 15
Professional PHP4 Programming
A Sample LDAP Application in PHP Page 17
|