The Server Pages
:: TSP Menu
- Home
- Authors
- Glossary
- RSS Feed

:: Servers
- CPanel
- Hosting
- Linux
- Windows

:: Webmaster
- Databases
- Design
- Search Engines

:: Scripts
- Scripts

:: Documentation
- PHP Manual

:: Other
- Errors & Solutions
- TechPunt
- Wojjie

search for in the

ldap_set_option> <ldap_sasl_bind
[edit] Last updated: Sat, 12 May 2012

view this page in

ldap_set_option> <ldap_sasl_bind
[edit] Last updated: Sat, 12 May 2012
add a note add a note User Contributed Notes ldap_search
kandsobrien at gmail dot com 16-Feb-2012 03:52
I wanted to look up some information from various fields of our Active Directory LDAP server. I thought I would contribute the results of that research here:

  Bind to an Active Directory LDAP server and look
  something up.
$SearchFor="fred";               //What string do you want to find?
$SearchField="samaccountname";   //In what Active Directory field do you want to search for the string?

$LDAPHost = "";       //Your LDAP server DNS Name or IP Address
$dn = "DC=whatever,DC=whatever"; //Put your Base DN here
$LDAPUserDomain = "@something.something"//Needs the @, but not always the same as the LDAP server domain
$LDAPUser = "ldapuserid";        //A valid Active Directory login
$LDAPUserPassword = "passforuser";
$LDAPFieldsToFind = array("cn", "givenname", "samaccountname", "homedirectory", "telephonenumber", "mail");
$cnx = ldap_connect($LDAPHost) or die("Could not connect to LDAP");
ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3);  //Set the LDAP Protocol used by your AD service
ldap_set_option($cnx, LDAP_OPT_REFERRALS, 0);         //This was necessary for my AD to do anything
ldap_bind($cnx,$LDAPUser.$LDAPUserDomain,$LDAPUserPassword) or die("Could not bind to LDAP");
error_reporting (E_ALL ^ E_NOTICE);   //Suppress some unnecessary messages
$filter="($SearchField=$SearchFor*)"; //Wildcard is * Remove it if you want an exact match
$sr=ldap_search($cnx, $dn, $filter, $LDAPFieldsToFind);
$info = ldap_get_entries($cnx, $sr);
  for (
$x=0; $x<$info["count"]; $x++) {
    if (
stristr($sam, "$SearchFor") && (strlen($dir) > 8)) {
"\nActive Directory says that:\n";
"CN is: $nam \n";
"SAMAccountName is: $sam \n";
"Given Name is: $giv \n";
"Telephone is: $tel \n";
"Home Directory is: $dir \n";
  if (
$x==0) { print "Oops, $SearchField $SearchFor was not found. Please try again.\n"; }
Jean-Loup 01-Feb-2012 06:27
Example of parallel search :

=array('dmdName=users,dc=foo,dc=fr','dmdName=users,dc=bar,dc=com');  // two basedn
$filter='(&(objectClass=inetOrgPerson)(uid=*))'// single filter

$cnx = ldap_connect('localhost',389); // single connection
ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3);

ldap_bind($cnx,'uid=root,dc=foo,dc=fr','password');  // authentication on two BDB

$search = ldap_search(array($cnx,$cnx),$basedn,$filter,$attributes);  // search

// result
info at acpower dot biz 19-Sep-2011 03:07
I'm a newbie, so I hope this helps some other newbie with a head scratcher...

This code returned an error of 'No Such Object':


= ldap_search ($ldapcon, "cn=admin,dc=acpower,dc=biz", "(filters)");


I took out the cn, and magic! it works:


= ldap_search ($ldapcon, "dc=acpower,dc=biz", "(filters)");

nick 01-Sep-2011 11:09
Results from ActiveDirectory may be ordered by objectSid.
We can get all users for each page size by modify filter.

// ... connect to ldap
while (
1) {
$filter = '(objectClass=user)';
    if (
strlen($lastsid)) {
$v)=array_values(unpack('V',substr($lastsid,24))); // id for user.
$s = substr($lastsid,0,24).pack('V',1+$v); // next sid.
$s = preg_replace('/../','\\\\$0',bin2hex($s)); // escape for fiter
$filter = '(&'.$filter.'(objectSid>='.$s.'))'; // fiter for next entries.
$res = ldap_search($ldap,$basedn,$filter,array('objectSid','cn'));
    if (!
ldap_count_entries($ldap,$res)) {
    for (
$ent=ldap_first_entry($ldap,$res); $ent; $ent=ldap_next_entry($ldap,$ent)) {
$lastsid) = ldap_get_values_len($ldap,$ent,'objectSid');
Arnold 11-May-2011 01:35
I have been working on a script where I needed to get all the users who were member of a specific MS AD group. Because of PHP bug #42060 ( ) I could not get all the users back who were member of the group.
After googling for a day I found an article and a patch but it required that I downloaded the source code for php 5.1.6 or 5.2.10 run the patch and than recompile the code to fix the problem.
Problem was
1) I am not a Linux goeroe so I was not very comfortable doing this....
2) I am running the script on a production machine with other code using PHP and did not know what the consequence would bee for that code.
3) I could not update PHP anymore because in newer versions this patch would probably not work any more.

But yesterday I saw the light and wrote some code to get around this problem, maybe other people can use it that have the same problem.

= "(&(memberOf=" .$ADGroup. "))";
$startResults        = ldap_search($ldapconnect, $userBase, $startFilter, $attr);
$countResult        = ldap_count_entries($ldapconnect,$startResults);

$countResult == 1000 OR $countResult == 1500)
// loop trough the number 97-122 (ASCII number for the characters a-z)
// translate the number to a character
$character            = chr($a);
// the new search filter withs returns all users with a last name starting with $character
$filter            = "(&(sn=$character*)(memberOf=$ADGroup))";
$results        = ldap_search($ldapconnect, $userBase, $filter, $attr);
$countResult2    = ldap_count_entries($ldapconnect,$results);
// See if the search for all users starting with a specific character still hits the search limit
        // if so than do a new search to find all the users where the last name starts with "aa" and
        // than with "ab", "ac" etc. etc
        // In the best case we can now find 675.324 users per group when the search limit is 1000
        // ((26 * 999  for the fist character) * 26 for the second character)
        // and 1.013.324 when the search limit is 1500
If($countResult2 == 1000 or $countResult2 == 1500)
$character2    = chr($b);
$filter2    = "(&(sn=$character$character2*)(memberOf=$ADGroup))";
$results2    = ldap_search($ldapconnect, $userBase, $filter2, $attr);
$count2        = ldap_count_entries($ldapconnect,$results2);   
$entries2    = ldap_get_entries($ldapconnect,$results2);                       
// do your thing
$entries            = ldap_get_entries($ldapconnect,$results);
// do your thing
$entries            = ldap_get_entries($ldapconnect,$startResults);
// do your thing
David Fontanella 26-Jan-2010 06:39
To get all attributes + special attributes:

(..., $filter, array('*','createtimestamp','modifytimestamp'));

* -> all attributes (normally requested by default)
the special attributes you want
ben _at_ 19-Jan-2010 02:11
Following from my note of 11-Nov-2009 06:56 regarding DN issues when using LDAP instead of the Global Catalog when querying AD, further investigation was showing that although the results were in the packet, I was getting an error instead:

'Search: Can't contact LDAP server' AKA Error 81.

Using more detailed analysis:


echo $error


Referral: ldap:// DC=DomainDnsZonesDC=defg,DC=de,DC=abc,DC=ac,DC=uk

By using trial and error, the error went away and results returned when using:

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ben _at_ onshop_co_uk 11-Nov-2009 10:56
When searching Active Directory, if you are not getting all the attributes back you are expecting such as AD system/hidden attributes such as 'employeeType' then check the following:

First, ensure you are not connecting to the Global Catalog port (e.g. 3269/3268). You need to connect to an LDAP port such as 636 (SSL) or 389 (non-SSL).

Second, check the DN you are binding with when changing from the Global Catalog port to an LDAP port. I found that a DN without an OU returned a 'Search: Can't contact LDAP server' error. For example this fails:


Whilst adding the OU to the DN returned an error free result:


If you consequently need to interrogate multiple DNs then an array of DNs can be passed to ldap_search.
ben _at_ onshop_co_uk 11-Nov-2009 10:24
Example to illustrate searching more than one DN (multiple DNs):



$id[] = $ds;
$id[] = $ds;

$filter = 'samaccountname='.$_POST['username'];
$result = ldap_search($id,$dn,$filter);

$search = false;

foreach (
$result as $value) {
$search = $value;

$info = ldap_get_entries($ds, $search);
$info = 'No results found';
eugene at hutorny dot in dot ua 24-Oct-2009 11:35
This function accepts LDAP search results and return a flat table (2-d array) with search results.
 * This function returns flat table out of search results
 * $ad - a valid connection to Active Directory (returned by ldap_connect)
 * $sr - a search result (returned by ldap_search)
 * $key- an attribute name to be used as the key in the resulting array
 * Returns 2-d array as the following:
 *   return_value["keyfieldvalue"]["attributename"] = "attribute value"; // entries with key filed present
 *  return_value[i]["attributename"] = "attribute value"; // entries with key fields missing
function ldap_flatresults($ad,$sr,$key=false) {
  for (
$entry=ldap_next_entry($ad,$entry)) {
$user = array();
$attributes = ldap_get_attributes($ad,$entry);
$i=$attributes['count'];$i-- >0;) {
$user[strtolower($attributes[$i])] = $attributes[$attributes[$i]][0];
$key && $user[$key] )
$users[strtolower($user[$key])] = $user;
$users[] = $user;
rtdees at gapac dot com 09-Oct-2009 01:13
As of today, I have found for me that ldap_search and ldap_list are reversed in functionality.  ldap_list now searches the subtree and ldap_search does not.  This is witnessed when searching against an AD forest running on Windows 2008 in what I believe is 2003 mode.
john dot saterfiel at act dot org 29-Sep-2009 10:10
Here's an example of how to connect to an active directory (2003 windows ad tested). And retrieve a specific person's information when given only their username (sAMAccountName).  Note: I have noticed that some active directory servers do care about what case the attributes are in and others don't.  This site was very useful in looking up the AD attributes but I did have to lowercase them all to work for me.
Do a google search on "active directory person attributes" to find the site.

I doubt the code below will work for everybody as is but it should give ad users a good start in how to get a logged in user's data without knowing what organization or security group they're in.  This was needed because my company didn't put all their users in the same organization.

= '';
$ldap_domain = '';
$ldap_dn = "dc=mycomp,dc=com";

$ds = ldap_connect( $ldap_url );
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);

$username = "your_user_name_here";
//must always check that password length > 0
$password = "your_password_here";

// now try a real login
$login = ldap_bind( $ds, "$username@$ldap_domain", $password );
'- Logged In Successfully<br/><br/>';
$attributes = array("displayname", "mail",
$filter = "(&(objectCategory=person)(sAMAccountName=$username))";

$result = ldap_search($ds, $ldap_dn, $filter, $attributes);

$entries = ldap_get_entries($ds, $result);

$entries["count"] > 0){
//echo print_r($entries[$i],1)."<br />";
echo "<b>User Information:</b><br/>";
"displayName: ".$entries[0]['displayname'][0]."<br/>";
"email: ".$entries[0]['mail'][0]."<br/>";
"department: ".$entries[0]['department'][0]."<br/>";
"title: ".$entries[0]['title'][0]."<br/>";
"office: ".$entries[0]['physicaldeliveryofficename'][0]."<br/>";
//echo "manager: ".$entries[$i]['manager'][0]."<br/>";
$manager_result = ldap_search($ds,

$manager_entries = ldap_get_entries($ds, $manager_result);
$manager_entries["count"] > 0){
"manager: ". $manager_entries[0]['displayname'][0];
Exception $e){
'<br/><br/>- Logged Out';
douglass_davis at earthlink dot net 08-Apr-2009 06:01
A better ldap_escape, if you don't need nested filters such as those in the Pear package.  Escapes for both filters and distinguished names.

function ldap_escape($str, $for_dn = false)
// see:
    // RFC2254
if  ($for_dn)
$metaChars = array(',','=', '+', '<','>',';', '\\', '"', '#');
$metaChars = array('*', '(', ')', '\\', chr(0));

$quotedMetaChars = array();
    foreach (
$metaChars as $key => $value) $quotedMetaChars[$key] = '\\'.str_pad(dechex(ord($value)), 2, '0');
$str=str_replace($metaChars,$quotedMetaChars,$str); //replace them
return ($str);
beni at php dot net 27-Aug-2008 02:17
Please note, that your example is not fully implementing filter escaping needs and is thus not safe for every case (see RFC 2254).

Filter stuff is also available in pears Net_LDAP:

With this class you can easily create nested filters without worrying for escaping issues (those are handled by the class itnernally in a rfc compatible maner).
metala at metala dot org 11-Jun-2008 02:12
// Escape string
// see: RFC2254
function ldap_escape($str){
    $metaChars = array('\\', '(', ')', '#', '*');
    $quotedMetaChars = array();
    foreach ($metaChars as $key => $value) $quotedMetaChars[$key] = '\\'.dechex(ord($value));
    $str=str_replace($metaChars,$quotedMetaChars,$str); //replace them
    return ($str);
chrisbloom7 at gmail dot com 08-Aug-2007 01:18
Here are a couple of resources for proper construction of filters.

Before finding these I had been stumped for hours on how to do something like "all users starting with "a" except those from OU 'foo'"
beni at php dot net 25-Jun-2007 11:56
LDAP stuff is very nicely capsulated in the object oriented Net_LDAP class provided by PEAR:
lifo at liche dot net 23-May-2007 11:39
When I discovered I couldn't get searches to work with complex strings (in my case searching on displayName which can have parens and slashes in it). I made this quick function to quote ldap strings in accordance with the RFC. Except I encode spaces as well since searching wouldn't work with spaces. Note, technically speaking a search filter can be encoded into the \xx format for all characters but then filters wouldn't be human readable.

I'm somewhat surprised there wasn't a built in ldap_quote() type of function already.
// see: RFC2254
function ldap_quote($str) {
'\\', ' ', '*', '(', ')' ),
'\\5c', '\\20', '\\2a', '\\28', '\\29' ),
Allie 06-Mar-2007 02:38
I just posted on the ldap_bind, but I figured it couldn't hurt here since this was the first place I stopped when trying to figure out my problem.  My error pointed to ldap_search, but specifying the ldap_connect port was the fix.

When you want to search the entire directory for MS AD, you must specify port 3268 in your bind.  This is also true for apache auth_ldap.

 $ldapserver = ldap_connect($server,3268);
Alain SCHNERB 05-Mar-2007 05:44
I had problem searching into Microsoft Active Directory
with ldap_search.

System administrator does not want to change the 1.000 limit
of returned result because of Domain Controler performance.

Here is a example of code that activates the Page Mode.

See "searching with ActiveX Data Objects (ADO)" on MSDN
for more details.

$connection = New COM("ADODB.Connection");
$commande = New COM("ADODB.Command");
$resultat = New COM("ADODB.Recordset");
$connection->Provider = "ADsDSOObject";
$commande->ActiveConnection = $connection ;
$commande->Properties["Cache results"] = false;

$commande->Properties["Page size"] = 1000;

$recherche1 = "<LDAP://OU=XXXX,OU=Ressources_Locales,DC=COMMUN,
$recherche2 = ";(&(objectCategory=group)

$commande->commandtext = $recherche1.$recherche2;
$resultat = $commande->Execute();

$count = 0;
while (!$resultat->eof())
    if ($count<10)
        echo $resultat["distinguishedname"]."<br>";       
    $count = $count +1;
echo $count."<br>";
cbrinker at contronicssolutions dot com 23-Jan-2007 02:18
I was completely lost trying to setup LDAP access with a Windows Server 2003 environment, but I finally got it to work. Here's a lifesaving tip:

-Script/web server cannot be located on the Active Directory server that you are querying

As well, here's the sample code I used:

//This code cannot be executed on the same server as AD is installed on!!!
$ad = ldap_connect("ad server");
//Set some variables
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
//Bind to the ldap directory
$bd = ldap_bind($ad,"","password")
        or die(
"Couldn't bind to AD!");

//Search the directory
$result = ldap_search($ad, "OU=orginizational unit,DC=domain,DC=com", "(CN=*)");

//Create result set
$entries = ldap_get_entries($ad, $result);
//Sort and print
echo "User count: " . $entries["count"] . "<br /><br /><b>Users:</b><br />";

    for (
$i=0; $i < $entries["count"]; $i++)
$entries[$i]["displayname"][0]."<br />";

//never forget to unbind!
buhreen at shaw dot ca 03-Apr-2006 09:12
If you are just trying to run LDAP searches against Active Directory, you might find it easier to use the COM objects and use the ADSI ldap search function.  This allows you to use SQL based LDAP queries.  It also allows you to perform subtree level searches in AD.

Here is a quick example.


= New COM("ADODB.Connection");
$RS = New COM("ADODB.Recordset");

$Conn->Provider = "ADsDSOObject";
$Conn->Properties['User ID'] = "CN=ZimZam,CN=Users,DC=corp,DC=ad,DC=bob,DC=prv";
$Conn->Properties['Password'] = "anythingyouwant";
$strConn = "Active Directory Provider";

$strRS = "Select givenname,sn,displayName,mail,SAMAccountName from 'LDAP://,DC=ad,DC=bob,DC=prv' where objectClass='user' and SAMAccountName='abc123';

$RS->Open($strRS, $Conn, 1, 1);
$RS['givenname'] ." - ". $RS['sn'] ." - ". $RS['displayName'] ." - ". $RS['mail'] ." - ".  $RS['SAMAccountName'] ."<br>";

27-Jan-2006 03:53
HOWTO list LDAP users.

This CODE list one user from LDAP tree, but I' like list all user from LDAP one ou=Organization


= 'cn=user,dc=domain,dc=org';
$ldappass = 'password';
$sdn = 'cn=user,ou=group,dc=domain,dc=org';

$ldapconn = ldap_connect("ldap://localhost", 389)
or die(
"Not connect: $ldaphost ");

if (
$ldapconn) {

// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

// verify binding
if ($ldapbind) {
$justthese = array("uid");

$sr=ldap_read($ldapconn, $srdn, $filter, $justthese);
$entry = ldap_get_entries($ldapconn, $sr);

} else {
"LDAP conn ok...";



echo $entry[0]["mail"][0] . " mail adress ";
$entry[0]["sn"][0] . " Name ";
cruzfern at chuchuwa dot com dot ar 30-Aug-2005 09:14
The internal attributes (like createTimestamp, modifyTimestamp, etc), don't come by default (when the optional parameter attributes is not set). You have to specify it:

fmouse at fmp dot com 01-Mar-2005 10:53
It appears that the Netscape Directory SDK ( referenced for LDAP filter information is no longer accepting connections.   The A copy of RFC 2254 which defines the standard for string representations of LDAP filters can be found  at
openldap at mail dot doris dot cc 11-Feb-2005 07:54
PHP 4.3.10

I was trying to do an ldapsearch without a basedn.  First, I tried with ' ', as suggested above, but it gave me invalid dn syntax error.

$sr=ldap_search($ds, ' ', $filter);
Warning: ldap_search(): Search: Invalid DN syntax in ...

Then I changed it to
$sr=ldap_search($ds, "", $filter);

Which gave me the following error:
Warning: ldap_search(): Search: No such object in ...

With that I then modified my ldap.conf file and commented out the BASE field
#BASE   dc=example, dc=com

Then it worked!

So it looks like if you supply a blank basedn, then it will use your default basedn in ldap.conf.
rsu_friend at yahoo dot com 11-Feb-2005 01:03
I was doing a ldap_search with
$searchbasedn = "miDomainName=" . $_SESSION['selectDomain'] ."," . LDAP_DOMAINBASE;
$filter = "(&(mpsAccountNumber=". $acctNumber .")(objectclass=mpsAccountDetails))";   
$attributes = array("mpsparentchild");

 $sr = ldap_search($ldapconn, $searchbasedn, $filter,$attributes); 

For some reasone this search was failing
but I was able to do successful search only when I gave the search filter as
$filter = "(&(mpsAccountNumber= $acctNumber )(objectclass=mpsAccountDetails))";   

I did not get why the ldap_search was not able to search in the first case.
sema at technion dot ac dot il 04-Sep-2004 10:54
In order to perform the searches on Windows 2003 Server Active Directory you have to set the LDAP_OPT_REFERRALS option to 0:

ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

Without this, you will get "Operations error" if you try to search the whole AD schema (using root of the domain as a $base_dn).

As opposed to Windows 2000 Server, where this option was optional and only increased the performance.
chester at the dot underground dot com dot au 20-Nov-2003 01:45
If you are searching active directory and are experiencing lag or time outs, it may be that you are being given ldap referrals from the ldap server. The following code will disable this.

($connect, LDAP_OPT_REFERRALS, 0);
sembiance at cosmicrealms dot com 16-Nov-2003 06:15
When searching for BINARY data (such as an Active Directory objectGUID) you need to escape each hexadecimal character with a backslash.

The following command line run of ldapsearch shows:
ldapsearch -b "dc=blahblah,dc=com" "(objectGUID=\AE\C3\23\35\F7)"

In PHP, you need to escape the escape for the backslash:
ldap_search($ds,"dc=blahblah,dc=com", "(objectGUID=\\AE\\C3\\23\\35\\F7)");
francis dot tyers at hp dot com 10-Nov-2003 07:53
it seems that all fields must be used in lower case even if they are mixed case in the ldapsearch output.


gidNumber: 1010
homeDirectory: /home/dnt

must be:

echo "gid: " . $info[$i]["gidnumber"][0] . "<br>";
echo "home directory: ". $info[$i]["homedirectory"][0] ."<br>";

not ( $info[$i]["homeDirectory"][0] ) etc.
nicolas at atanis dot net 19-Aug-2003 11:17
Here is a little script that make a complete subtree search ( i know a script above seems do that but it doesnt work fine)
This is my version:

Voila ce que j'ai fait aujourd'hui ...

      $ldap_host = "";
    $ldap_port = "389";
    $base_dn = "dc=fr";
    $filter = "(cn=*)";
    $ldap_user ="cn=admin,dc=fr";
    $ldap_pass = "hellodelu";
    $connect = ldap_connect( $ldap_host, $ldap_port);
    ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);

    $bind = ldap_bind($connect, $ldap_user, $ldap_pass);
    $read = ldap_search($connect, $base_dn, $filter);
    $info = ldap_get_entries($connect, $read);
    echo $info["count"]." entrees retournees<BR><BR>";
    for($ligne = 0; $ligne<$info["count"]; $ligne++)
        for($colonne = 0; $colonne<$info[$ligne]["count"]; $colonne++)
            $data = $info[$ligne][$colonne];
            echo $data.":".$info[$ligne][$data][0]."<BR>";
        echo "<BR>";

me at gavinadams dot org 15-Aug-2003 01:38
Minor clarification on AD LDAP searchs. Small typo in previous example, and does not display multiple values per attribute. Here's the for loop to enumerate all entries, attributes, and values:

$bind = ldap_bind($connect) // asume anon connect or add user/pass
     or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
     or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<br>";
// $i = entries
// $ii = attributes for entry
// $iii = values per attribute
for ($i = 0; $i<$info["count"]; $i++) {
  for ($ii=0; $ii<$info[$i]["count"]; $ii++){
     $data = $info[$i][$ii];
     for ($iii=0; $iii<$info[$i][$data]["count"]; $iii++) {
       echo $data.":&nbsp;&nbsp;".$info[$i][$data][$iii]."<br>";
echo "<p>"; // separate entries
php @ fccfurn dot com 11-Apr-2003 03:35
To do subtree search from top DN in Active Directory, Make sure you do your ldap_set_option().

= "";
$base_dn = "DC=php,DC=net";
$filter = "(cn=Joe User)";
$ldap_user  = "CN=Joe User,OU=Sales,DC=php,DC=net";
$ldap_pass = "pass";
$connect = ldap_connect( $ldap_host, $ldap_port)
         or exit(
">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($connect, $ldap_user, $ldap_pass)
      or exit(
">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
      or exit(
">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
$info["count"]." entries returned<p>";
for (
$i=0; $ii<$info[$i]["count"]; $ii++){
$data = $info[$i][$ii];
Kamil Kukura <kamk at nexen dot cz> 26-Feb-2003 09:20
When I tried to search with empty base DN on OpenLDAP server which had "" namingContext I got result "no such object". In the log file there was query for dn: dc=example,dc=com (!).
As a workaround, it seems it's enough to feed it with space (' ') as base DN - ldap_search($ds, ' ', '(...filter...)', ...
neumeyed at city dot bloomington dot in dot us 29-Jan-2003 04:50
A previous comment noted: "I've also noticed that the departmentNumber, employeeNumber (and maybe others in inetorgperson.schema) are not returned from a search."

This is incorrect. These attributes are returned, but you must reference them with lowercase names. That is, instead of doing this:


Do this:


This doesn't seem like "correct" behavior to me, but I don't know enough about LDAP to say for sure.
nick dot veitch at futurenet dot co dot 17-Jan-2003 08:59
It might be useful to list here the operators that work:

=         - matches exact value
=*xxx  - matches values ending xxx
=xxx*  - matches values beginning xxx
=*xxx* - matches values containing xxx
=*       - matches all values (if set - NULLS are not returned)

>=xxx  - matches everthing from xxx to end of directory
<=xxx  - matches everything up to xxx in directory

~=xxx      - matches similar entries (not all systems)

Boolean operators for constructing complex search

&(term1)(term2)  - matches term1 AND term2
| (term1)(term2)  - matches term1 OR term2
!(term1)                 - matches NOT term1
&(|(term1)(term2))(!(&(term1)(term2)) - matches XOR term1 term2

some of the more compelx constructions seem to work with varying  degrees of efficiency - sometimes it can be better to filter some of the results with the search and do further filtering in PHP.
emrecio at netscape dot net 30-Sep-2002 08:42
implode(", ",$uentry[0]["rfc822mailalias"]);

doesn't work as expected because "count" is in there... one /must/ use the 'for' loop to cycle through results (discarding "count" element).
jpdalbec at ysu dot edu 09-Sep-2002 07:33
I've found that spaces need to be escaped in search filters ("\20"), at least using the Red Hat PHP 4.1.2 package.  Otherwise no results are returned.
john_taylor_1973 at yahoo dot com 27-Jun-2002 02:26
Try to use ldap_list(), if possible.  It is much faster.  ldap_search searches a scope of LDAP_SCOPE_SUBTREE, but ldap_list searches a scope of just LDAP_SCOPE_ONELEVEL.  This made a big difference on Novell eDirectory 8.6.1, even for a query that only returned 130 objects.  Using an attribute list, the 4th function parameter (of either function), also made queries faster.
31-Aug-2001 07:13
I used the following to retrieve all entries from an ILS (Netmeeting) Server:<p>    $sr=ldap_search($ds, "objectclass=rtperson","(&(cn=%)(objectclass=rtperson))");
<p>Have fun!
cdaveb at csua dot berkeley dot edu 02-Jan-2001 05:23
FYI, for those doing LDAP searches on Exchange servers, there seems to be some preference in Exchange to disallow searches that aren't initial searches (i.e. only x* will work, not * or *x). I'd been going nuts trying to figure out why I kept getting errors doing * searches.

More info at:
aa529 at nospamchebucto dot ns dot ca 22-Nov-1999 01:27
Be careful of special characters when generating filters from user input.

*, (, ), \ and NUL should be backslash-escaped. See section 4 of RFC 2254 (I found it here:

show source | credits | sitemap | contact | advertising | mirror sites