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.ldap_search
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
ldap_search
Референца за `function.ldap-search.php` со подобрена типографија и навигација.
ldap_search
(PHP 4, PHP 5, PHP 7, PHP 8)
ldap_search — Search LDAP tree
= NULL
LDAP\Connection|array
$ldap,array|string
$base,array|string
$filter,array
$attributes = [],int
$attributes_only = 0,int
$sizelimit = -1,int
$timelimit = -1,int
$deref = LDAP_DEREF_NEVER,?array
$controls = null): LDAP\Result|array|false
Performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory.
It is also possible to perform parallel searches. In this case, the first argument should be an array of
LDAP\Connection Можно е да се вршат и паралелни пребарувања. Во овој случај, првиот аргумент треба да биде низа од LDAP\Connection инстанци, наместо една. Ако пребарувањата не треба да ја користат истата основна DN и филтер, наместо тоа може да се помине низа од основни DN и/или низа од филтри како аргументи. Овие низи мора да бидат со иста големина како низата од LDAP\Result инстанци, бидејќи првите записи од низите се користат за едно пребарување, вторите записи се користат за друго, и така натаму. При паралелно пребарување се враќа низа од false.
Параметри
ldap-
Еден LDAP\Connection инстанца, вратена од ldap_connect().
base-
инстанци, освен во случај на грешка, кога вратената вредност ќе биде
filter-
The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the » Netscape Directory SDK or » RFC4515 for full information on filters).
attributes-
An array of the required attributes, e.g.
array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.Основна DN за директориумот.
attributes_only-
Користењето на овој параметар е многу поефикасно од стандардното дејство (кое е враќање на сите атрибути и нивните поврзани вредности). Затоа, употребата на овој параметар треба да се смета за добра пракса.
sizelimit-
Треба да се постави на 1 ако се сакаат само типови на атрибути. Ако се постави на 0 се преземаат и типови на атрибути и вредности на атрибути, што е стандардно однесување.
Забелешка:
Ви овозможува да го ограничите бројот на преземени записи. Поставувањето на ова на 0 значи без ограничување.
Овој параметар НЕ МОЖЕ да ја надмине серверски поставената големина. Можете да ја поставите пониско.
timelimit-
Некои сервери за директориуми ќе бидат конфигурирани да враќаат не повеќе од однапред поставен број на записи. Ако ова се случи, серверот ќе покаже дека вратил само делумен сет на резултати. Ова се случува и ако го користите овој параметар за да го ограничите бројот на преземени записи.
Забелешка:
Го поставува бројот на секунди колку што се троши на пребарувањето. Поставувањето на ова на 0 значи без ограничување.
deref-
Овој параметар НЕ МОЖЕ да ја надвладее временската граница поставена на серверот. Сепак, можете да ја поставите пониско.
-
LDAP_DEREF_NEVERСпецифицира како нонaметата треба да се третираат за време на пребарувањето. Може да биде една од следниве опции: - (стандардно) нонaметата никогаш не се дереференцираат. - нонaметата треба да се дереференцираат за време на пребарувањето, но не и при лоцирање на основниот објект на пребарувањето. - нонaметата треба да се дереференцираат при лоцирање на основниот објект, но не и за време на пребарувањето. - нонaметата секогаш треба да се дереференцираат. -
LDAP_DEREF_SEARCHINGда се испрати со барањето. -
LDAP_DEREF_FINDINGинстанца, низа од -
LDAP_DEREF_ALWAYSинстанци, или
-
controls-
Низа од LDAP контроли сега е nullable; претходно, стандардно беше
Вратени вредности
Враќа LDAP\Result Примерот подолу ги презема организациската единица, презимето, името и адресата на е-пошта за сите лица во "Мојата компанија" каде што презимето или името го содржи поднизот LDAP\Result . Овој пример користи буловски филтер за да му каже на серверот да бара информации во повеќе од еден атрибут. false при неуспех.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.1.0 |
На ldap параметарот очекува LDAP\Connection
инстанца сега; претходно, валидна ldap link resource се очекуваше.
|
| 8.1.0 | Враќа LDAP\Result инстанца сега; претходно, а resource . |
| 8.0.0 |
controls Пример #1 LDAP пребарување [].
|
| 7.3.0 |
Поддршка за controls added
|
Примери
nick dot veitch at futurenet dot co dot $personjayleno at yahoo dot com
aa529 at nospamchebucto dot ns dot ca
<?php
// $ds is a valid LDAP\Connection instance for a directory server
// $person is all or part of a person's name, eg "Jo"
$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array("ou", "sn", "givenname", "mail");
$sr=ldap_search($ds, $dn, $filter, $justthese);
$info = ldap_get_entries($ds, $sr);
echo $info["count"]." entries returned\n";
?>Белешки од корисници 33 белешки
<?php
set_time_limit(30);
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);
// config
$ldapserver = 'svr.domain.com';
$ldapuser = 'administrator';
$ldappass = 'PASSWORD_HERE';
$ldaptree = "OU=SBSUsers,OU=Users,OU=MyBusiness,DC=myDomain,DC=local";
// connect
$ldapconn = ldap_connect($ldapserver) or die("Could not connect to LDAP server.");
if($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to bind: ".ldap_error($ldapconn));
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...<br /><br />";
$result = ldap_search($ldapconn,$ldaptree, "(cn=*)") or die ("Error in search query: ".ldap_error($ldapconn));
$data = ldap_get_entries($ldapconn, $result);
// SHOW ALL DATA
echo '<h1>Dump all data</h1><pre>';
print_r($data);
echo '</pre>';
// iterate over array and print data for each entry
echo '<h1>Show me the users</h1>';
for ($i=0; $i<$data["count"]; $i++) {
//echo "dn is: ". $data[$i]["dn"] ."<br />";
echo "User: ". $data[$i]["cn"][0] ."<br />";
if(isset($data[$i]["mail"][0])) {
echo "Email: ". $data[$i]["mail"][0] ."<br /><br />";
} else {
echo "Email: None<br /><br />";
}
}
// print number of entries found
echo "Number of entries found: " . ldap_count_entries($ldapconn, $result);
} else {
echo "LDAP bind failed...";
}
}
// all done? clean up
ldap_close($ldapconn);
?>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:
http://www.cis.ohio-state.edu/htbin/rfc/rfc2254.html)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 ( http://bugs.php.net/bug.php?id=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.
<?PHP
$startFilter = "(&(memberOf=" .$ADGroup. "))";
$startResults = ldap_search($ldapconnect, $userBase, $startFilter, $attr);
$countResult = ldap_count_entries($ldapconnect,$startResults);
IF($countResult == 1000 OR $countResult == 1500)
{
// loop trough the number 97-122 (ASCII number for the characters a-z)
For($a=97;$a<=122;$a++)
{
// 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)
{
For($b=97;$b<=122;$b++)
{
$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
}
}
Else
{
$entries = ldap_get_entries($ldapconnect,$results);
// do your thing
}
}
}
else
{
$entries = ldap_get_entries($ldapconnect,$startResults);
// do your thing
}
?>Can an example using the new $serverctrls parameter please be added? I have no idea how to use this.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:
<?
$r=ldap_search($ds,$base,$filter,array("createTimestamp"));
?>Here are a couple of resources for proper construction of filters.
http://msdn2.microsoft.com/En-US/library/aa746475.aspx
http://technet.microsoft.com/en-us/library/aa996205.aspx
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'"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)");it seems that all fields must be used in lower case even if they are mixed case in the ldapsearch output.
example:
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.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:
http://www.microsoft.com/Exchange/en/55/help/documents/server/XOG16007.HTMExample of parallel search :
<?php
$basedn=array('dmdName=users,dc=foo,dc=fr','dmdName=users,dc=bar,dc=com'); // two basedn
$filter='(&(objectClass=inetOrgPerson)(uid=*))'; // single filter
$attributes=array('dn','uid','sn');
$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
ldap_bind($cnx,'uid=root,dc=bar,dc=com','password');
$search = ldap_search(array($cnx,$cnx),$basedn,$filter,$attributes); // search
// result
for($i=0;$i<count($search);$i++){
print_r(ldap_get_entries($cnx,$search[$i]));
print "\n";
}
?>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 = "192.168.0.50";
$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>";
}
ldap_close($connect);
--------
nicolasIn 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.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.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.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.
<?
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
?>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.": ".$info[$i][$data][$iii]."<br>";
}
}
echo "<p>"; // separate entriesI ran into the problem, that the attribute I was search for had the matching rule of "exactMatch".
Example:
E-Mail Address is stored in mixed case: [email protected]
LDAP Search will not retrieve any values when the user enters: [email protected]
Solution: instead of comparing user input and attribute value by
<?php
if($data[$i]['mail'][0] == $username) {
// this will run into nothing
}
?>
use strcasecmp instead:
<?php
if(strcasecmp($data[$i]['mail'][0], $username) == 0) {
// works
}A big warning sign must be placed on `$filter` field.
The filter MUST be present and it MUST NOT be empty.
Else you will receive mysterious "Can't contact LDAP server" error and no help from google.
The single clue could be found when running `ldapsearch` CLI tool to verify your code - in verbose mode, it clearly states that, in absence of user-specified filters, it adds an `(objectclass=*)` filter to avoid an error.
```
$ ldapsearch -H ldaps://dc2.ads.darkdragon.lan -vvv -b 'CN=Users,DC=ads,DC=darkdragon,DC=lan
filter: (objectclass=*)
requesting: All userApplication attributes
# extended LDIF
#
# LDAPv3
# base <CN=Users,DC=ads,DC=darkdragon,DC=lan> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#
…
```Example code from my ldap class.
public function query($_filter, $_att, $_ref=2, $count_bool=true)
{
$fn = 'query';
$config = $this->config;
$conn = $this->conn;
if (!$conn)
{return $this->errorConnection($fn);}
ldap_set_option($conn, LDAP_OPT_DEREF, $_ref);
$result = ldap_search($conn, $config['baseDn'], $_filter, $_att); // or die(ldap_error($conn))
if ($result===false)
{
$this->error("Search error, neexistuje!");
return false;
}
$count = ldap_count_entries($conn, $result);
if ($count_bool && $count!=1)
{
$this->error("Search error, neni unikatni! count=".$count);
ldap_free_result($result);
return false;
}
$data = ldap_get_entries($conn, $result);
ldap_free_result($result);
return $data;
}
// ---
$filter = "(&(objectclass=person)(cn=" . $user_name . "))";
$att = array(
'uid',
'workforceID',
'employeeID',
'givenName',
'sn',
'mail'
);
$data = $this->query($filter, $att, 2, true);While developing a plugin, I had to search users on LDAP server using ldap_search() command and it was not finding them, but ldapsearch command in unix shell (ubuntu) did.
Problem was few lines above in my code, around ldap_connect(). For server address I input ldap://server.hostname, which turned to be the culprit.
Once I used only server.hostname, without protocol (ldap://), users where found and shown correctly.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);To do subtree search from top DN in Active Directory, Make sure you do your ldap_set_option().
<?php
$ldap_host = "pdc.php.net";
$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);
echo $info["count"]." entries returned<p>";
$ii=0;
for ($i=0; $ii<$info[$i]["count"]; $ii++){
$data = $info[$i][$ii];
echo $data.": ".$info[$i][$data][0]."<br>";
}
ldap_close($connect);
?>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!
<p>KeesExample to illustrate searching more than one DN (multiple DNs):
<?php
$ds=ldap_connect($ldapserver);
$dn[]='OU=ABC,DC=xyz,DC=ac,DC=uk';
$dn[]='OU=DEF,DC=xyz,DC=ac,DC=uk';
$id[] = $ds;
$id[] = $ds;
$filter = 'samaccountname='.$_POST['username'];
$result = ldap_search($id,$dn,$filter);
$search = false;
foreach ($result as $value) {
if(ldap_count_entries($ds,$value)>0){
$search = $value;
break;
}
}
if($search){
$info = ldap_get_entries($ds, $search);
}else{
$info = 'No results found';
}
?>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:
ldap_get_option($ds,LDAP_OPT_ERROR_STRING,$error);
echo $error
Displayed:
Referral: ldap://DomainDnsZones.defg.de.bc.ac.uk/ 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);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.
ie:
$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.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...)', ...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:
$entries[0]["departmentNumber"][0]
Do this:
$entries[0]["departmentnumber"][0]
This doesn't seem like "correct" behavior to me, but I don't know enough about LDAP to say for sure.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':
<?php
$search = ldap_search ($ldapcon, "cn=admin,dc=acpower,dc=biz", "(filters)");
?>
I took out the cn, and magic! it works:
<?php
$search = ldap_search ($ldapcon, "dc=acpower,dc=biz", "(filters)");
?>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).It appears that the Netscape Directory SDK (developer.netscape.com) 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 http://www.ietf.org/rfc/rfc2254.txtResults from ActiveDirectory may be ordered by objectSid.
We can get all users for each page size by modify filter.
<?php
// ... connect to ldap
$lastsid='';
while (1) {
$filter = '(objectClass=user)';
if (strlen($lastsid)) {
list($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)) {
break;
}
for ($ent=ldap_first_entry($ldap,$res); $ent; $ent=ldap_next_entry($ldap,$ent)) {
list($lastsid) = ldap_get_values_len($ldap,$ent,'objectSid');
}
}
?>