Create an LDAP Address Book with PHP - Setup Public LDAP Server Information
(Page 2 of 6 )
The first thing we need to do is define all of the LDAP servers we might want to search.
"LDAP_NAME" = The name of the new LDAP entry.
"LDAP_SERVER" = The IP address or hostname of the new LDAP entry.
"LDAP_ROOT_DN" = The root distinguished name of the new LDAP entry. <?php
$LDAP_NAME = "Netscape Net Center";
$LDAP_SERVER = "memberdir.netscape.com";
$LDAP_ROOT_DN = "ou=member_directory,o=netcenter.com";
$LDAP_NAME = "Bigfoot";
$LDAP_SERVER = "ldap.bigfoot.com";
$LDAP_ROOT_DN = "";
//If no server chosen set it to 0
?> Create LDAP Query
As mentioned previously, LDAP queries are not much like SQL queries. Therefore, the syntax may seem a bit limiting, but here is a basic example and one that works in this scenario. //Create Query $ldap_query = "cn=$common";
In our example "cn" is the attribute on which we are performing the search, and $common is the search string variable from the search form.
LDAP query syntax allows for wildcard matching using '*'. For example, '*stanley' will find 'dan stanley'. Connect to LDAP Server
The given function connects to an LDAP resource and assigns the connection link identifier to a variable, much like connecting to a regular database, like MySQL. <?php
//Connect to LDAP
$connect_id = ldap_connect($LDAP_SERVER[$SERVER_ID]);
In our example, "$connect_id" is the link identifier, $LDAP_SERVER is the array of possible ldap servers, and $SERVER_ID is the LDAP server variable from the search form. Process Query if Connection Was Successful
If our connection was successful, we will have a valid LDAP link identifier and we can process the query. <?php
$bind_id = ldap_bind($connect_id);
$search_id = ldap_search($connect_id, $LDAP_ROOT_DN[$SERVER_ID], $ldap_query);
//Assign Result Set to an Array
$result_array = ldap_get_entries($connect_id, $search_id);
//Echo Connection Error
echo "Could not connect to LDAP server: $LDAP_SERVER[$SERVER_ID]";
Once we have established a connection to the LDAP services, we must identify ourselves. Most database connections with PHP send the username and password with the connection.
However, with LDAP, credentials are unknown until a bind is performed. In our example, "$bind_id" is the bind link identifier.
We are performing an anonymous bind to the public LDAP servers. Therefore, no argument is sent to ldap_bind() accept the connection link identifier.
After we have been authorized, via bind as anonymous, we perform the query using the ldap_search() function. $search_id is created and is our search link identifier.
Then, we assign our result set to the variable $result_array using the function ldap_get_entries(). This will allow us to sort the information in a logical manner for display.
blog comments powered by