Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : LDAP Functions

LDAP Functions

Introduction

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.

Requirements

You will need to get and compile LDAP client libraries from either » OpenLDAP or » Bind9.net in order to compile PHP with LDAP support.

Installation

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. To enable SASL support, be sure --with-ldap-sasl[=DIR] is used, and that sasl.h exists on the system.

Note to Win32 Users:

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the systems PATH), it is not recommended. This extension requires the following files to be in the PATH: libeay32.dll and ssleay32.dll

Versions before PHP 4.3.0 additionally require libsasl.dll.

In order to use Oracle LDAP libraries, proper Oracle environment has to be set.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 155. LDAP configuration options

Name Default Changeable Changelog
ldap.max_links "-1" PHP_INI_SYSTEM  


For further details and definitions of the PHP_INI_* constants, see the Appendix I, php.ini directives.

Resource Types

Most LDAP functions operate on or return resources (e.g. ldap_connect() returns a positive LDAP link identifier required by most LDAP functions).

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at 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_NETWORK_TIMEOUT (integer)
Option for ldap_set_option() to allow setting network timeout. (Available as of PHP 5.3.0)
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)

Examples

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

Example 1109. 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 . "<br />";

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

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

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

   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] . "<br /><hr />";
   }

   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"

Table of Contents

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 — Alias of ldap_unbind()
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_sasl_bind — Bind to LDAP directory using SASL
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

Code Examples / Notes » ref.ldap

scott

You can find a PHP class that works well with Active Directory here:
http://www.wiggumworld.com/adldap/


rusko dot marton

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.


xxoes

Yes you musst use LDAP with SSL!
$newPassword = "\"" . $new_password . "\"";
$len = strlen($newPassword);
$newPassw = "";
for($i=0;$i<$len;$i++)
  $newPassw .= "{$newPassword{$i}}\000";
$userdata["unicodepwd"] = $newPassw;
ldap_mod_replace($dn, $userdata);
My Windows php binary "PHP Version 4.3.9" dos not support LDAP with SSL, i have use stunnel to create a ssl connection.


ant

When working with LDAP, its worth remembering that the majority
of LDAP servers encode their strings as UTF-8. What this means
for non ascii strings is that you will need to use the utf8_encode and
utf8_decode functions when creating filters for the LDAP server.
Of course, if you can its simpler to just avoid using non-ascii characters
but for most sites the users like to see their strange native character
sets including umlauts etc..
If you just get ? characters where you are expecting non-ascii, then
you might just need to upgrade your PHP version.


jabba

When using PHP on windows, and you are trying to connect (bind) to a Netware (6) LDAP server that requires secure connections (LDAPS), PHP will return a message stating that the server cannot be found.

A network traffic capture of the traffic taking place on connection attempt reveals that the server supplies a certificate for use in the SSL connection, but this is rejected (***bad certificate SSLv3 packet) by the client.
The reason for this is probably that the PHP LDAP implementation tries to verify the received certificate with the CA that issued the certificate. There may be a way to make it possible that this verification succeeds, but it is also possible to disable this verification by the client (which is, in this case, PHP) by creating an openldap (surprise!!) configuration file.
The location of this configuration file seems to be hardcoded in the LDAP support module for windows, and you may need to manually create the following directory structure:
C:\openldap\sysconf\
In the sysconf folder, create a text file named 'ldap.conf' (you can use notepad for this) and, to disable certificate verification, place the following line in the ldap.conf file:
TLS_REQCERT never
After this, all the normal ldap_bind calls will work, provided your supplied user id and password are correct.


knitterb

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! :)


webmaster

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 !


mleaver

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.


wtfo

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;
}
}
}


paul

This note is for people trying to load extensions which require additional dlls on W2k/XP.
As stated in the installation notes one has to copy those libraries to %SystemRoot%\system32 directory.
Generally it's not a good idea to copy files from left to right and back especially for the system folder.
The result is always a mess. I hope you'll find my way to get things working for more elegant than just copying files.
Leave those dlls where they are in dlls folder under PHP's installation path. Then edit environment variables so that the system variable PATH to include the dlls' folder. You may need to reboot the system. That's all, nice and clean.
One who doesn't know what I'm talking about should go this way:
My Computer - > Control Panel -> System -> Advanced -> Environment Variables ... -> System variables.


richie bartlett

This is an update to <i>wtfo at technocraft dot com</i> (23-May-2002 03:40)... This function allows additional (optional) parameters. The prev function listed, failed to close the ldap connection after successful authenication.
<?php
function checkNTuser($username,$password,$DomainName="myDomain",
                     $ldap_server="ldap://PDC.example.net"){//v0.9
// returns true when user/pass enable bind to LDAP (Windows 2k).
$auth_user=$username."@".$DomainName;
#echo $auth_user."->";
if($connect=@ldap_connect($ldap_server)){
#echo "connection ($ldap_server): ";
if($bind=@ldap_bind($connect, $auth_user, $password)){
#echo "true
";
@ldap_close($connect);
return(true);
}//if bound to ldap
}//if connected to ldap
#echo "failed
";
@ldap_close($connect);
return(false);
}//end function checkNTuser
?>


pookey

This is an example of how to query an LDAP server, and print all entries out.
<?php
$ldapServer = '127.0.0.1';
$ldapBase = 'DC=anlx,DC=net';
/*
* try to connect to the server
*/
$ldapConn = ldap_connect($ldapServer);
if (!$ldapConn)
{
 die('Cannot Connect to LDAP server');
}
/*
* bind anonymously
*/
$ldapBind = ldap_bind($ldapConn);
if (!$ldapBind)
{
 die('Cannot Bind to LDAP server');
}
/*
* set the ldap options
*/
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
/*
* search the LDAP server
*/
$ldapSearch = ldap_search($ldapConn, $ldapBase, "(cn=*)");
$ldapResults = ldap_get_entries($ldapConn, $ldapSearch);
for ($item = 0; $item < $ldapResults['count']; $item++)
{
 for ($attribute = 0; $attribute < $ldapResults[$item]['count']; $attribute++)
 {
   $data = $ldapResults[$item][$attribute];
   echo $data.":&nbsp;&nbsp;".$ldapResults[$item][$data][0]."
";
 }
 echo '<hr />';
}
?>


sukhruprai

There is an article about how to compile openldap on windows. Openldap binaries are also available for download (for windows).
http://www.fivesight.com/downloads/openldap.asp


gerbille

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


jector

Spent some time on fixing "Unable to load dynamic library 'php_ldap.dll'. Copied libeay32.dll and ssleay32.dll  everywhere, but error still stands.
After digging all this dlls I found, that both libeay32.dll and ssleay32.dll need msvcr70.dll (or msvcr71.dll, it depends on the compiler version). Then just copy that dll to system32\ dir and it works perfectly.


yorch

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.


maykelsb

Problems with ldap_search in W2k3, can be solved adding
// -- $conn is a valid ldap connection.
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($conn, LDAP_OPT_REFERRALS,0);
before ldap_bind, as sad in http://bugs.php.net/bug.php?id=30670.


egeczi

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.

tod

Notes for people running PHP 4 with Apache 2.2 on Win2k3.
The Apache Service needs to be running under the local administrators account in order for the ldap_connect to return a result. As apposed to the Domain Administrators account as may happen on servers in an Active Directory Domain.
It will 'appear' to work ok but will return no results otherwise.
so use (server name)\administrator for the username in the service logon properties.
Tod


ron

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. ;-)


nliu99

libsasl.dll is NOT required for ldap functionalities. Go check out the posting at: http://bugs.php.net/bug.php?id=9485
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. user@company.com
2. It's easiest to search for user info with ldap_search by filtering: (userprincipalname=[user])


brudinie

LDAP Active Directory Last Logon (lastlogon).
This took me an entire day to work out. If you want to get the last logon date from an active directory account, you have to convert it from AD time stamp to unix time stamp.
Once you've got a unix time stamp, PHP can format it as a date.
Here is the code to do it:
       $dateLargeInt=$info[$i]["lastlogon"][0]; // nano seconds (yes, nano seconds) since jan 1st 1601
       $secsAfterADEpoch = $dateLargeInt / (10000000); // seconds since jan 1st 1601
       $ADToUnixConvertor=((1970-1601) * 365.242190) * 86400; // unix epoch - AD epoch * number of tropical days * seconds in a day
       $unixTsLastLogon=intval($secsAfterADEpoch-$ADToUnixConvertor); // unix Timestamp version of AD timestamp
       $lastlogon=date("d-m-Y", $unixTsLastLogon); // formatted date


christopherbyrne

Just an ammendment to my previous post: my calculations were using east coast Australian time (GMT+10) whereas the Unix timestamp is in GMT. Therefore Active Directoy's "accountexpires" integer value does start from 1-Jan-1601 00:00:00 GMT and the number of seconds between this date and 1-Jan-1970 00:00:00 GMT is 11644524000.
The increments are still definately in 100 nanoseconds though!


unroar

In Solaris 9 the libnet library is a prerequisite for building  PHP with LDAP, SASL and SSL (libnet is available on Sunfreeware).  
I didn't see this mentioned anywhere and I'm not sure if it is required by ldap or sasl or ssl.  I just spent an hour on Google with no luck before I figured it out, maybe this comment will help the next googler.
The error is,
ld: fatal: library -lnet: not found
ld: fatal: File processing errors. No output written to sapi/cli/php
collect2: ld returned 1 exit status
make: *** [sapi/cli/php] Error 1


hijinio

In case anybody has trouble configuring PHP with LDAP support on a Solaris 10 box, here is the configure line I used:
./configure --with-nsapi=/opt/SUNWwbsvr --enable-libgcc --disable-libxml --with-ldap=/usr/local --prefix=/opt/php/php-5.0.4
The important part to note is the location used for --with-ldap= ; which for most S10 people, will be "--with-ldap=/usr/local".


mike

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 firstname.lastname@domainname.com
This can be used to bind to AD. I've not seen any difference in any of the methods.


dmeehan

If your having problems running LDAP searches on the base DC against Active Directory 2k3, you need to set dsHeuristics to 0000002 in Active Directory. This allows searches to function similar to how they did in Active Directory 2k2. You can update dsHeuristics by launching ldp.exe goto 'connection' and create a new connection. Then goto bind and bind to your ldap server. Next select the 'Browse' menu and choose 'modify'. The DN *might* look like this:
CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=mycompany,DC=com
Attribute is: dsHeuristics
Value is: 0000002
Set the operation to replace and you should be set.
This solves the 'Operations error' error that happens when attempting to search without specifying an OU.
-d


nacenroe

If you're looking to use PHP to integrate LDAP with AD (I'm working with Win2K3), you may want to tinker with the LDP.exe tool included (no resource kit needed!!) with Win2k and Win2K3.  You can run this app right from the command line.
The Win2K3 Help function was a good start point, and then pointed me to an article in the M$ KB: http://support.microsoft.com/default.aspx?scid=kb;en-us;255602 (XADM: Browsing and Querying Using the LDP Utility).
So ... if your connect/bindings are working but your queries are not, you may want to start here.  I'm finding it very useful when I run it on the local AD to see the attributes, etc.


alex

If you want to use ldaps on windows but you don't want to validate the tls certificate try the following line before the ldap_connect call:
putenv('LDAPTLS_REQCERT=never') or die('Failed to setup the env');


jimmy wimenta oei

If you want to disable/enable chase referral option, you need to first set the protocol version to version 3, otherwise the LDAP_OPT_REFERRALS option will not have any effect. This is especially true for querying MS Active Directory.
<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
?>
And as always, these should be called after connect but before binding.


ooja

If you bind anonymousely to a Windows 2003 Server (Active Directory) and you perform a ldap_search you will get an search operations error. You have to use a login and a password when binding!
I personally found alot of good information here:
http://www.scit.wlv.ac.uk/~jphb/sst/php/extra/ldap.html


gcathell

I recently had to access a Microsoft Active Directory server as an LDAP service over SSL using PHP.  It took me a long time to get all the information I needed to get it to work.
I attempted to post a note here with the details but it ended it being too long.  I've placed the details at the following URL in hopes that someone else will benefit and will be able to solve the problem much more quickly than I did.
http://greg.cathell.net/php_ldap_ssl.html
Good luck!


yapt

I have found this new site with a lot of information about LDAP:
http://www.ldapzone.com/


sami oksanen

I edited Jon Caplinger's code which is located below (date: 09-Nov-2002 05:44).
- I corrected line
  "if (!($connect=@ldap_connect($ldap))) {" with
  "if (!($connect=@ldap_connect($ldap_server))) {"
- Removed $name-attribute
- "Name is:"-field was always an Array, so I changed printing line to:
  " echo "Name is: ". $info[$i]["name"][0]."
";"
I also added some alternative search filters to try out.
Here is the code:
<?php
$ldap_server = "ldap://foo.bar.net";
$auth_user = "user@bar.net";
$auth_pass = "mypassword";
// Set the base dn to search the entire directory.
$base_dn = "DC=bar, DC=net";
// Show only user persons
$filter = "(&(objectClass=user)(objectCategory=person)(cn=*))";
// Enable to show only users
// $filter = "(&(objectClass=user)(cn=$*))";
// Enable to show everything
// $filter = "(cn=*)";
// connect to server
if (!($connect=@ldap_connect($ldap_server))) {
    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");
}
//if (!($bind=@ldap_bind($connect))) {
//     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"][0]."
";
  echo "Display name is: ". $info[$i]["displayname"][0]."
";
  echo "Email is: ". $info[$i]["mail"][0]."
";
  echo "Telephone number is: ". $info[$i]["telephonenumber"][0]."

";
}
?>


bounty_arz

Hi,
There is a way to Access Active Directory :
- You will have to bind as admin :
eg: administrator@yourdomain.com
or as a user :
eg: fschultz@yourdomain.com
(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
http://www.imphar.com


jon dot caplinger

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 = "bgates@microsoft.com";
$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];
}


spam2004

Here are two small functions that enables you to convert a binary objectSID from Microsoft AD into a more usefull text version (formatted (S-1-5.....)).
// Converts a little-endian hex-number to one, that 'hexdec' can convert
function littleEndian($hex) {
for ($x=strlen($hex)-2; $x >= 0; $x=$x-2) {
$result .= substr($hex,$x,2);
}
return $result;
}
// Returns the textual SID
function binSIDtoText($binsid) {
$hex_sid=bin2hex($binsid);
$rev = hexdec(substr($hex_sid,0,2));   // Get revision-part of SID
$subcount = hexdec(substr($hex_sid,2,2)); // Get count of sub-auth entries
$auth = hexdec(substr($hex_sid,4,12));   // SECURITY_NT_AUTHORITY
$result = "$rev-$auth";
for ($x=0;$x < $subcount; $x++) {
$subauth[$x] = hexdec(littleEndian(substr($hex_sid,16+($x*8),8)));  // get all SECURITY_NT_AUTHORITY
$result .= "-".$subauth[$x];
}
return $result;
}
echo binSIDtoText($bin_sid);


greatsafari

Having seen so many variations of methods for connecting and query the Active Directory server, it really makes me suspect that the whole thing is dependent of the Active Directory configurations. Looking at this post at:
http://www.phpbuilder.com/mail/php-general/2003022/1459.php
Some methods proven to be working in one instance failed at another instance.


mrowe

FWIW,
Before anyone else wastes a day scratching their head wondering why they can't search Active Directory...
I wasn't able to search on Active Directory until I did this (immediately after the ldap_connect):
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
I was able to ldap_bind if I didn't set this option, but I kept receiving errors.  Also note, I had to set the option BEFORE binding.


jpmens

Further to jabba at zeelandnet dot nl's note. If you are trying to connect to an LDAPS URI with OpenLDAP, you can either create the configuration file as described by jabba, or alternatively, use the environment settings to set LDAPTLS_REQCERT=never as described in ldap.conf(5).

php ^ pixelcop , com

For those trying to do LDAP authentication with Lotus Domino NAB, the following has worked for me (based on the win2k example by webmaster@autourdupc.com) :
$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>";


hkemale

For IIS+PHP+NTFS file system user
After copied <php_dir>/dlls/*.dll to <windows>/systems32/ remember to add read and exexcute premission to "everyone" and the extensions *.dll. this can prevent warning of Access is denied of php_ldap.dll


christopherbyrne

For anyone who's been having trouble working with the "accountexpires" attribute in Active Directory after having read the following article
www.microsoft.com/technet/scriptcenter/
resources/qanda/sept05/hey0902.mspx
or something similar, this may save you some frustration. In the article is is mentioned that this attribute is an integer representing the number of nanoseconds since 01-Jan-1601 00:00:00.
However the "accountexpires" attribute actually seems to be the number of 100 nanosecond increments since 31-Dec-1600 14:00:00. As a result if you divide the integer by 10,000,000 and subtract 11644560000 you will get a Unix timestamp that will match the dates in AD.
To set the "accountexpires" date just reverse the procedure, that is, get the timestamp for the new date you want, add 11644560000 and multiply by 10,000,000. You will also need to format the resultant number to make sure it is not outputted in scientific notation for AD to be happy with it.
Hope this helps!


nigelf

Chasing referrals in Active Directory (ie: searching across domains), can be slow.  You can look up the object instead in the GC (Global Catalog) as follows:
Remove any reference to ldap:// when you use ldap_connect, ie: use "serv1.mydom.com" NOT "ldap://serv1.mydom.com"
Connect to port 3268 (not 389, the default)
Set the Base DN for the search to null ie: "" (empty quotes).  
AD will then run the search against the GC which holds a copy of all objects in the Forest.  You can also retrieve a subset of attributes (including group membership, except local groups).
You will still need to follow referals for a full set of attributes.


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker