 |
ldap_search (PHP 3, PHP 4, PHP 5) ldap_search -- Search LDAP tree Descriptionresource ldap_search ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]] )
Returns a search result identifier or FALSE on error.
ldap_search() 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. base_dn specifies the base DN
for the directory.
There is an optional fourth parameter, that can be added to
restrict the attributes and values returned by the server to just
those required. This is much more efficient than the default
action (which is to return all attributes and their associated
values). The use of the fourth parameter should therefore be
considered good practice.
The fourth parameter is a standard PHP string 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.
Note too that some directory server hosts will be configured to
return no more than a preset number of entries. If this occurs,
the server will indicate that it has only returned a partial
results set. This occurs also if the sixth parameter
sizelimit has been used to limit the count
of fetched entries.
The fifth parameter attrsonly should be
set to 1 if only attribute types are wanted.
If set to 0 both attributes types and attribute values are fetched
which is the default behaviour.
With the sixth parameter sizelimit it is
possible to limit the count of entries fetched.
Setting this to 0 means no limit.
NOTE: This parameter can NOT override server-side preset sizelimit.
You can set it lower though.
The seventh parameter timelimit sets the number
of seconds how long is spend on the search.
Setting this to 0 means no limit.
NOTE: This parameter can NOT override server-side preset timelimit.
You can set it lower though.
The eighth parameter deref specifies how aliases
should be handled during the search. It can be one of the following:
LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search
but not when locating the base object of the search.
LDAP_DEREF_FINDING - aliases should be dereferenced when
locating the base object but not during the search.
LDAP_DEREF_ALWAYS - aliases should be dereferenced always.
注:
These optional parameters were added in 4.0.2:
attrsonly,
sizelimit,
timelimit,
deref.
The search filter can be simple or advanced, using boolean
operators in the format described in the LDAP documentation (see
the Netscape Directory SDK
for full information on filters).
The example below retrieves the organizational unit, surname,
given name and email address for all people in "My Company" where
the surname or given name contains the substring $person. This
example uses a boolean filter to tell the server to look for
information in more than one attribute.
例子 1. LDAP search
<?php // $ds is a valid link identifier 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"; ?>
|
|
From 4.0.5 on it's also possible to do parallel searches. To do this
you use an array of link identifiers, rather than a single identifier,
as the first argument. If you don't want the same base DN and the
same filter for all the searches, you can also use an array of base DNs
and/or an array of filters. Those arrays must be of the same size as
the link identifier array since the first entries of the arrays are
used for one search, the second entries are used for another, and so
on. When doing parallel searches an array of search result
identifiers is returned, except in case of error, then the entry
corresponding to the search will be FALSE. This is very much like
the value normally returned, except that a result identifier is always
returned when a search was made. There are some rare cases where the
normal search returns FALSE while the parallel search returns an
identifier.
buhreen at shaw dot ca
04-Apr-2006 12: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.
<?php
$Conn = 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";
$Conn->Open($strConn);
$strRS = "Select givenname,sn,displayName,mail,SAMAccountName from 'LDAP://corp.ad.bob.prv/DC=corp,DC=ad,DC=bob,DC=prv' where objectClass='user' and SAMAccountName='abc123';
$RS->Open($strRS, $Conn, 1, 1);
echo $RS['givenname'] ." - ". $RS['sn'] ." - ". $RS['displayName'] ." - ". $RS['mail'] ." - ". $RS['SAMAccountName'] ."<br>";
$RS->Close;
$Conn->Close;
?>
27-Jan-2006 07:53
HOWTO list LDAP users.
This CODE list one user from LDAP tree, but I' like list all user from LDAP one ou=Organization
<?php
$ldaprdn = '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) {
$filter="uid=*";
$justthese = array("uid");
$sr=ldap_read($ldapconn, $srdn, $filter, $justthese);
$entry = ldap_get_entries($ldapconn, $sr);
} else {
echo "LDAP conn ok...";
}
}
ldap_close($ldapconn);
?>
<?php
echo $entry[0]["mail"][0] . " mail adress ";
echo $entry[0]["sn"][0] . " Name ";
?>
cruzfern at chuchuwa dot com dot ar
31-Aug-2005 12: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:
<?
$r=ldap_search($ds,$base,$filter,array("createTimestamp"));
?>
fmouse at fmp dot com
02-Mar-2005 02:53
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.txt
openldap at mail dot doris dot cc
11-Feb-2005 11: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.
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.
rsu_friend at yahoo dot com
11-Feb-2005 05: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
05-Sep-2004 01: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 05: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.
<?
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
?>
sembiance at cosmicrealms dot com
17-Nov-2003 10: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 11:53
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.
nicolas at atanis dot net
20-Aug-2003 02: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 = "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);
--------
nicolas
me at gavinadams dot org
16-Aug-2003 04: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.": ".$info[$i][$data][$iii]."<br>";
}
}
echo "<p>"; // separate entries
php @ fccfurn dot com
12-Apr-2003 06:35
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);
?>
Kamil Kukura <kamk at nexen dot cz>
27-Feb-2003 01: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
30-Jan-2003 08: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:
$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.
nick dot veitch at futurenet dot co dot
18-Jan-2003 12: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
01-Oct-2002 11: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 10: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
28-Jun-2002 05: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.
01-Sep-2001 10: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!
<p>Kees
|  |