PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<java_last_exception_getldap_8859_to_t61>
view the version of this page
Last updated: Tue, 22 Apr 2003

XLVIII. LDAP functions

Introductie

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 in HTML format.

Afhankelijkheden

You will need to get and compile LDAP client libraries from either the University of Michigan , or to compile PHP with LDAP support.

Installatie

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libsasl.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)

Configuratie tijdens scriptuitvoer

Het gedrag van deze functies wordt be�nvloed vanuit php.ini.

Tabel 1. LDAP configuration options

NameDefaultChangeable
ldap.max_links"-1"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Resource types

Deze extensie maakt geen gebruik van resources.

Voorgedefineerde constanten

Deze constanten worden gedefineerd door deze extensie, en zullen alleen beschikbaar zijn als de extensie met PHP is meegecompileerd, of als deze dynamisch is geladen vanuit een script.

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)

Voorbeelden

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

Voorbeeld 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"

Inhoudsopgave
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 add a note
ron at opus1 dot com
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. ;-)

mleaver at scis dot ecu dot edu dot au
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.

ian at eiloart dot comNOSPAM
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.
yapt at techNOSPAMnovell dot com
14-Oct-2001 11:37

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

bounty_arz at hotmail dot com
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

j dot parree at net-communications dot de
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

webmaster at autourdupc dot com
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 !

bob dot brown at opus dot co dot nz
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>";

sukhruprai at yahoo dot com
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).

wtfo at technocraft dot com
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;
}
}
}

knitterb at blandsite dot org
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! :)

JoshuaStarr at aelana dot com
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!

rusko dot marton at gibzone dot hu
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.

mike at whisperedlies dot org
09-Sep-2002 04:41

In addition to the netBIOS suggestion above, when binding to a Windows2k AD server, you can use the UPN of the intended user. For instance, if your SAM account name is firstname.lastname and your domain is domainname.com, your UPN might be [email protected]

This can be used to bind to AD. I've not seen any difference in any of the methods.

gerbille at free dot fr
10-Oct-2002 01:26

The MD5 of PHP returns a result encoded in base16. But the LDAP MD5 returns a string encoded in base64.
$pwd="toto";
$pwd_md5=base64_encode(mhash(MHASH_MD5,$pwd));
Just add "{MD5}" front $pwd_md5 to obtain the same format as LDAP directory.

Bye
Aur�lia

nospam-mark@atarexDOTcom
23-Oct-2002 07:06

Beware when linking to LDAP libraries:
Solaris 8 comes with some by default, and you may have installed Netscape LDAP C SDK as well,
but OpenLDAP defaults to use /usr/local

So know thy SDK - I have many build problems
because I had Solaris 8, Netscape 3.0, Iplanet
5.0 and OpenLDAP libraries on my system.

jon dot caplinger at broadwing dot com
09-Nov-2002 05:44

Here is an example of searching active directory in w2k. Active directory requires a user account that has permissions to search the tree.

/* The following values are used for the example:
 1.  Domain = microsoft.com
 2.  Server =  unstable
 3.  User = bgates
 4. Password = iloveopensource
*/

// Get name value to search for from submitted form.

if (isset($HTTP_GET_VARS["name"])) {
    $name = $HTTP_GET_VARS["name"];
}

$ldap_server = "ldap://unstable.microsoft.com";
$auth_user = "[email protected]";
$auth_pass = "iloveopensource";

// Set the base dn to search the entire microsoft.com directory.

$base_dn = "DC=microsoft, DC=com";

/* filter the search for all people in the microsoft.com tree that have a name that matches any one of the following attributes name, displayname, or cn. */

$filter = "(&(objectClass=user)(objectCategory=person)
(|(name=$name*)(displayname=$name*)(cn=$name*)))";

// connect to server

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

// bind to server

if (!($bind=@ldap_bind($connect, $auth_user, $auth_pass))) {
    die("Unable to bind to server");  
}

// search active directory

if (!($search=@ldap_search($connect, $base_dn, $filter))) {
    die("Unable to search ldap server");
}

$number_returned = ldap_count_entries($connect,$search);
$info = ldap_get_entries($connect, $search);

echo "The number of entries returned is ". $number_returned;

for ($i=0; $i<$info["count"]; $i++) {
  echo "Name is: ". $info[$i]["name"];
  echo "Display name is: ". $info[$i]["displayname"][0];
  echo "Email is: ". $info[$i]["mail"][0];
  echo "Telephone number is: ". $info[$i]["telephonenumber"][0];
}

bens at effortlessis dot com
14-Nov-2002 12:34

PHP 4.2.3 and --with-ldap compiles nicely on RH 7.2 using the provided openldap rpms.

You do not need the Netscape SDK or the UofM versions installed. (isn't openldap derived from UofM version?)

This documentation indicates these other libraries which are un-necessary.

dave dot awatere at equant dot com
02-Dec-2002 10:50

When enabling ldap support for win32 binaries I ran into a few difficulties.  As previously mentioned here, the libsasl library is required for php_ldap.  Here are the two simple steps to getting this to work.

1. After sucessfully installing php and testing, copy the file libsasl.dll (google it for download sites, it's 40kb) to: C:/your_php_path/dlls.

2. Edit your php.ini and un-comment the line ;extension=php_ldap.dll  so that it reads extension=php_ldap.dll

Thats it.  Restart your webserver and test with <?php phpinfo();?>.

Note: if you have been fiddling with the location of libsasl.dll and you have an error "Unable to load dynamic library..." then you will need to kill the hung apache process (you can use taskinfo app for this) or restart you windows box after restoring you php.ini to original (no ldap_support).  I know this sounds confusing but it is the reason why I just wasted an hour and a half.  
 
I have tested this with all php versions from 4.1.2 up incl 4.3rc2.  Also have this running with apache2.  We use it with the xaraya.com cms to authenticate our intranet users.  Hope this saves some-one the hour and a half of pain it served me...

Christoph Grottolo
05-Jan-2003 11:40

libsasl.dll which is needed for php_ldap.dll to run on windows but not included in the actual release (4.3.0) is available as part of the open ldap binaries on .

Christoph

ldivinag at csuhayward dot edu
17-Jan-2003 12:31

well it's a no go for me.

using:

4.3.0
apache 1.3.27
win98 SE

i got a copy of LIBSASL.DLL from a 4.0.4xxx of php

and i copied it everywhere:

c:\windows
c:\windows\system
c:\windows\system32
c:\apache\apache <- where apache.exe sits
c:\php
c:\php\dlls
c:\php\extensions

and i still got the UNABLE TO LOAD...

should i go to apache2?

the version of LIBSASL is 40 k, but dated a year or so ago.  is there a specific version of it?

thanks...

leo d.

vdweij at mailsurf dot com
22-Jan-2003 04:25

I've had ldap up and running with php4.1.2 (win2000) and got problems upgrading to php4.3.0

I got an error saying could not load php_ldap.dll
The manual tells you to copy libsasl.dll into your winnt(/system32) folder, but that was already there????

Using the good old command prompt (move to php dir) and typing php.exe -? I got messages saying php needed other dll's, namely:
ssleay32.dll
libeay32.dll

Copying these dll's to the winnt(/system32) dir worked for me.

--May The Source Be With You--

Jaap Weel
05-Feb-2003 10:04

In some cases, when you're working on a system where PHP is pre-installed and you need to ask some mysterious and/or distant sysadmin to recompile it, you may want to forget about the LDAP functions and use the shell commands that seem to exist whenever the LDAP package is installed.

For example, I want to look up someone's e-mail address ("mail") in the Institute LDAP address book database and fetch from it their surname ("sn"). I use the backtick operator, which executes a shell command and returns its output to PHP:

$sn = `ldapsearch -h ldap-server.its.caltech.edu "(mail=$email)" sn | grep "sn:"`;
$sn = trim(str_replace("sn:","",$sn));

This probably isn't a good idea if you want complicated things, but for an occasional simple use it's a nice hack, I thought.

yorch at correo dot ath dot cx
03-Mar-2003 04:12

Some notes about running LDAP extension on a Win2k box:

After copying php_ldap.php and libsasl.dll in every single directory possible (c:\WinNT\System32, c:\php ...) I decided to read the installation.txt file.
The instructions to install php extensions say: "Some extra DLLs are required for some PHP extensions. Please copy the bundled dlls from the 'dlls/' directory in distribution package to your windows/system (Win9.x) or winnt/system32 (WinNT, Win2000, XP) directory. If you already have these DLLs installed on your system, overwrite them only if something is not working correctly."

So I did exactly that: copy ALL the dll files from "c:\php\dlls" to "c:\WinNT\System32".
Now they load beautifully ;-)

I hope this helps someone.

vattalai dot anil at st dot com
22-Mar-2003 02:50

Copying all dll files to WINNT/system32 directory?

I felt it is a crazy idea to do this just for ldap, but after fidiling with php_ldap for some time, I gave a try for it. And surprisingly it works!!! Thanks guys!

egeczi at nospamplease dot dist113 dot org
01-Apr-2003 05:05

On Win2k Server running IIS, it is not enough to just restart IIS after enabling the php_ldap extension. You have to restart the server itself.
nliu99 at nospam dot yahoo dot com
29-Apr-2003 10:09

libsasl.dll is NOT required for ldap functionalities. Go check out the posting at:

On win2k I followed these easy steps and got ldap to work:
1. copy php_ldap.dll from the extension folder to winnt/system32
2. edit winnt/php.ini so that ldap is enabled (uncomment the line).
3. restart IIS.
That's it and have fun with ldap.

A note for Microsoft Active Directory
1. You can login with the user email, i.e. [email protected]
2. It's easiest to search for user info with ldap_search by filtering: (userprincipalname=[user])

add a note add a note

<java_last_exception_getldap_8859_to_t61>
 Last updated: Tue, 22 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Sun May 25 21:10:51 2003 CEST