PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previousjava_last_exception_getldap_8859_to_t61next
Last updated: Tue, 03 Sep 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | French | German | Hungarian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Swedish | Turkish

XLVIII. LDAP functions

Introduzione

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.

Lots of information about LDAP can be found at

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

Requisiti

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 to compile PHP with LDAP support.

Istallazione

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap configuration option when compiling PHP to enable LDAP support.

Configurazione Runtime

Questa estensione non definisce alcuna direttiva di configurazione

Resource Type

Questa estensione non definisce alcun tipo di risorsa.

Costanti Predefinite

Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione � stata compilata nel PHP o se � stata caricata dinamicamente a runtime.

LDAP_DEREF_NEVER (integer)

LDAP_DEREF_SEARCHING (integer)

LDAP_DEREF_FINDING (integer)

LDAP_DEREF_ALWAYS (integer)

LDAP_OPT_DEREF (integer)

LDAP_OPT_SIZELIMIT (integer)

LDAP_OPT_TIMELIMIT (integer)

LDAP_OPT_PROTOCOL_VERSION (integer)

LDAP_OPT_ERROR_NUMBER (integer)

LDAP_OPT_REFERRALS (integer)

LDAP_OPT_RESTART (integer)

LDAP_OPT_HOST_NAME (integer)

LDAP_OPT_ERROR_STRING (integer)

LDAP_OPT_MATCHED_DN (integer)

LDAP_OPT_SERVER_CONTROLS (integer)

LDAP_OPT_CLIENT_CONTROLS (integer)

LDAP_OPT_DEBUG_LEVEL (integer)

GSLC_SSL_NO_AUTH (integer)

GSLC_SSL_ONEWAY_AUTH (integer)

GSLC_SSL_TWOWAY_AUTH (integer)

Esempi

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

Esempio 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

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"

Sommario
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_len -- Get all binary values from a result entry
ldap_get_values -- Get all 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
[email protected]
24-Feb-2000 12: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. ;-)

[email protected]
08-Mar-2001 08: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.

[email protected]
17-Jul-2001 06: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.
[email protected]
14-Oct-2001 11:37

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

[email protected]
26-Nov-2001 04: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

[email protected]
27-Nov-2001 01: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

[email protected]
31-Dec-2001 11: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 !

[email protected]
08-Jan-2002 10: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 08: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>";

[email protected]
05-May-2002 01:56

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

[email protected]
23-May-2002 10: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;
}
}
}

[email protected]
20-Jun-2002 03: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! :)

[email protected]
03-Jul-2002 10: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!

[email protected]
11-Jul-2002 12:06

You can authenticate to a Windows 2000 domain's ldap server easily by using the simplified netbios form of the username.

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

NO. You can use this form:

$user = "DOMAINNAME\\username"
$password = "Password_of_user";

if (!$connect = ldap_connect("<server>", <port>)) {
//error
exit;
}
if (!$res = @ldap_bind($ldap, $user, $password)) {
//error
exit;
}

It works fine with Active Directory, we use it.

add a note about notes
previousjava_last_exception_getldap_8859_to_t61next
Last updated: Tue, 03 Sep 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Fri Sep 6 12:35:50 2002 CEST