PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previousjava_last_exception_getldap_8859_to_t61next
Last updated: Tue, 28 May 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

XLIX. LDAP functions

Introduction to LDAP

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.

The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.

To refer to a file in a subdirectory on your hard disk, you might use something like


    /usr/local/myapp/docs
    

The forwards slash marks each division in the reference, and the sequence is read from left to right.

The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be.


    cn=John Smith,ou=Accounts,o=My Company,c=US
    

The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as ..


    country = US
    organization = My Company
    organizationalUnit = Accounts
    commonName = John Smith
    

In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.

Complete code example

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Esimerkki 1. LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is ".$ds."<p>";

if ($ds) { 
    echo "Binding ..."; 
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is ".$r."<p>";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds,"o=My Company, c=US", "sn=S*");  
    echo "Search result is ".$sr."<p>";

    echo "Number of entires returned is ".ldap_count_entries($ds,$sr)."<p>";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for ".$info["count"]." items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: ". $info[$i]["dn"] ."<br>";
        echo "first cn entry is: ". $info[$i]["cn"][0] ."<br>";
        echo "first email entry is: ". $info[$i]["mail"][0] ."<p>";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

Using the PHP LDAP calls

You will need to get and compile LDAP client libraries from either the University of Michigan ldap-3.3 package or the Netscape Directory SDK 3.0. You will also need to recompile PHP with LDAP support enabled before PHP's LDAP calls will work.

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:


  ldap_connect()    // establish connection to server
     |
  ldap_bind()       // anonymous or authenticated "login"
     |
  do something like search or update the directory
  and display the results
     |
  ldap_close()      // "logout"

More Information

Lots of information about LDAP can be found at

The Netscape SDK contains a helpful Programmer's Guide in .html format.

Sis�llys
ldap_8859_to_t61 --  Translate 8859 characters to t61 characters
ldap_add -- Add entries to LDAP directory
ldap_bind -- Bind to LDAP directory
ldap_close -- Close link to LDAP server
ldap_compare -- Compare value of attribute found in entry specified with DN
ldap_connect -- Connect to an LDAP server
ldap_count_entries -- Count the number of entries in a search
ldap_delete -- Delete an entry from a directory
ldap_dn2ufn -- Convert DN to User Friendly Naming format
ldap_err2str --  Convert LDAP error number into string error message
ldap_errno --  Return the LDAP error number of the last LDAP command
ldap_error --  Return the LDAP error message of the last LDAP command
ldap_explode_dn -- Splits DN into its component parts
ldap_first_attribute -- Return first attribute
ldap_first_entry -- Return first result id
ldap_first_reference --  Return first reference
ldap_free_result -- Free result memory
ldap_get_attributes -- Get attributes from a search result entry
ldap_get_dn -- Get the DN of a result entry
ldap_get_entries -- Get all result entries
ldap_get_option -- Get the current value for given option
ldap_get_values -- Get all values from a result entry
ldap_get_values_len -- Get all binary values from a result entry
ldap_list -- Single-level search
ldap_mod_add -- Add attribute values to current attributes
ldap_mod_del -- Delete attribute values from current attributes
ldap_mod_replace -- Replace attribute values with new ones
ldap_modify -- Modify an LDAP entry
ldap_next_attribute -- Get the next attribute in result
ldap_next_entry -- Get next result entry
ldap_next_reference --  Get next reference
ldap_parse_reference --  Extract information from reference entry
ldap_parse_result --  Extract information from result
ldap_read -- Read an entry
ldap_rename -- Modify the name of an entry
ldap_search -- Search LDAP tree
ldap_set_option -- Set the value of the given option
ldap_set_rebind_proc --  Set a callback function to do re-binds on referral chasing.
ldap_sort --  Sort LDAP result entries
ldap_start_tls --  Start TLS
ldap_t61_to_8859 --  Translate t61 characters to 8859 characters
ldap_unbind -- Unbind from LDAP directory
User Contributed Notes
LDAP functions
add a note about notes

24-Feb-2000 11:18

Note that when you are using loops to search through attributes, you must
handle [dn] separately, otherwise each iteration of the loop will only
return each character of the dn, left to right, and  the array for dn of
"cn=boo" would be:
dn [0]="c"
dn [1]="n"
dn [2]="="
dn [3]="b"
dn [4]="o"
dn [5]="o"
Not too much fun to debug. ;-)


08-Mar-2001 07:32

When authenticating to a Win2k LDAP server you must include the name of the
person authenticating to the server in the dn

i.e. cn=administrator, cn=users, dc=server, dc=domain, dc=country

Then when you bind to the LDAP database you use:

$res = ldap_bind($ldap, $dn, $password);

So a full example would be:

if (!($ldap = ldap_connect("<server>", <port>))) {
       die ("Could not connect to LDAP server");
}
$dn = "cn=administrator, cn=users, dc=myserver, dc=com, dc=au";
$password = "MyPassword";
if (!($res = @ldap_bind($ldap, $dn, $password))) {
       die ("Could not bind to $dn");
}

Then you do your list or search functions on the ldap database.


17-Jul-2001 05:34

Watch out. some of these functions return misleading errors if you are not
bound to the ldap server. For example, ldap_errno will tell you that it
has been passed an invalid link identifier.


14-Oct-2001 10:37

I have found this new site with a lot of information about LDAP:


26-Nov-2001 03:46

Hi, 

There is a way to Access Active Directory : 
- You will have to bind as admin :
eg: [email protected] 
or as a user :
eg: [email protected] 
(because you can't search the Subtree as anonymous). 

Then you can query, add, delete and modify entries if you respect the
syntax of the MS schema.

F.B


27-Nov-2001 12:01

Interoperability
Unix-PHP-LDAP based -> Active Directory (LDAP-server)

Well, We tried to use a superuser account but where are still not 
allowed to query important data like encrypted user passwords.

And that's because of the API Problem, as described above.

Right now I am working on a solution to use kerberos authentication 
to query the user against active directory.

For more Information about this try:


---------------------------------------
Solving this interoperability problem is still a big issue to many
developers.

J.J. Parree
Net communications GmbH
Cologne, Germany


31-Dec-2001 10:36

When authenticating to a Win2k LDAP server, the name of the person must be
the FULL NAME in the dn 

NB : nothing is case sensitive !

$dn="cn=DUPOND John, cn=Users, dc=autourdupc, dc=com"
$password = "Password_of_DUPOND"; 

Then when you bind to the LDAP database you use: 

if (!($ldap = ldap_connect("<server>", <port>))) { 
die ("Could not connect to LDAP server"); 
} 
if (!($res = @ldap_bind($ldap, $dn, $password))) { 
die ("Could not bind to $dn"); 
} 

Hope this will usefull for everyone !


08-Jan-2002 09:53

We have just reorganised our LDAP database to suit some of the responses
that Microsoft Outlook expects to receive.  As part of this I have
discovered that the names of the LDAP attributes returned have been
converted (by PHP I presume) to lower case.  This means that even though
the ldap attribute is "telephoneNumber", you must use
$info[0]["telephonenumber"][0] as
$info[$i]["telephoneNumber"][0] is not set.

Hope this helps someone :)

php ^ pixelcop , com
23-Apr-2002 07:33

For those trying to do LDAP authentication with Lotus Domino NAB, the
following has worked for me (based on the win2k example by
[email protected]) :

$ip = "localhost";
$dn="CN=Joe Blo, O=myOrganization";
$password = "password"; 

if (!($ldap = ldap_connect($ip))) { 
	die ("Could not connect to LDAP server"); 
} 

print "connected to <b>$ip</b><br/>";

if (!($res = @ldap_bind($ldap, $dn, $password))) { 
	die ("Could not bind to $dn"); 
} 

print "user <b>$dn</b> authenticated.<br/>";

$sdn = "O=myOrganization";
$filter = "(objectclass=*)";

print "executing search...<b>DN: $sdn; Filter:
$filter</b><br/>";
$sr=ldap_search($ldap, $sdn, $filter);

$info = ldap_get_entries($ldap, $sr);

print $info["count"]." entries returned<hr>"; 
print "<PRE>";
print_r($info);
print "</PRE>";


05-May-2002 12:56

There is an article about how to compile openldap on windows. Openldap
binaries are also available for download (for windows).


23-May-2002 09:40

This worked for me:

function checkNTUser ($username,$password) {
	$ldapserver = 'Your Server';
	$ds=ldap_connect($ldapserver); 
	if ($ds) {
		$dn="cn=$username,cn=Users, DC=[sitename], DC=[sitesuffix]";
		$r=@ldap_bind($ds,$dn,$password);   
		if ($r) { return true;
		} else {
			return false;
		}
	}
}


20-Jun-2002 02:48

When using PHP 4.2.1 with OpenLDAP 2.1.2 I was having problems with binding
to the ldap server.  I found that php was using an older protocol and
added the following to the slapd.conf:

allow bind_v2

See ``man slapd.conf'' for more info about the allow item in the
slapd.conf file, this is all I know! :)


03-Jul-2002 09:58

Behind the scenes, PHP is known to compile with the Netscape/iPlanet SDK
and those from OpenLDAP. We have successfully gotten the 32-bit Netscape
LDAP SDK for C v4.14 to compile into PHP on numerous platforms, most often
on Sun Solaris 2.6-2.8. We have never gotten the 64-bit 4.14 version to
work properly (at least on Solaris) nor have we gotten the 5.x versions to
work with PHP. Honestly, we didn't try hard with the 5.x versions because
we knew we could get v4.14 to work.

For our configuration, we specify the exact installation path for the C
SDK in the --with-ldap option. I think the default goes to /usr/local/ldap
if unspecified but I never trust the defaults for MySQL or LDAP (no
offense to anyone).

This is some basic historical information for those of you that may be
struggling to get LDAP into you PHP compilations. I hope it sheds some
light!

add a note about notes
previousjava_last_exception_getldap_8859_to_t61next
Last updated: Tue, 28 May 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat Jul 6 04:18:21 2002 CEST