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: http://pear.php.net/manual/en/package.networking.net-ldap.filter.php
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).
ldap_search
(PHP 4, PHP 5)
ldap_search — Recherche sur le serveur LDAP
Description
Effectue une recherche avec le filtre filter dans le dossier base_dn avec le paramétrage LDAP_SCOPE_SUBTREE. C'est l'équivalent d'une recherche dans le dossier. base_dn spécifie le DN de base du dossier.
Depuis PHP 4.0.5, il est possible de faire des recherches parallèles. Pour cela, vous devez utiliser un tableau de ressources de connexion comme premier argument, au lieu d'une ressource simple. Si vous ne voulez pas utiliser le même dossier de base DN et le même filtre pour toutes les recherches, vous pouvez aussi utiliser un tableau de DN et de filtres. Ces tableaux doivent alors être de la même taille que le tableau de ressources de connexion : la première entrée du tableau de ressources sera utilisée avec le premier DN et le premier filtre, etc. Lorsque vous faites une recherche parallèle, un tableau de résultats est retourné, sauf en cas d'erreur, auquel cas l'entrée contiendra FALSE. C'est très proche du comportement habituel, hormis le fait qu'un résultat est toujours retourné lorsqu'une recherche est faite. Il y a de rares cas où une recherche renvoie FALSE, alors qu'une autre en parallèle retourne un identifiant.
Liste de paramètres
- link_identifier
-
Un identifiant de lien LDAP, retourné par la fonction ldap_connect().
- base_dn
-
La base DN pour le dossier.
- filter
-
Le filtre de recherche peut être simple ou avancé, et utiliser ces opérateurs booléen au format décrit dans la documentation LDAP (reportez-vous à » Netscape Directory SDK pour plus d'informations sur les filtres).
- attributes
-
Un tableau d'attributs requis, e.g. array("mail", "sn", "cn"). Notez que le "dn" est toujours retourné, quelque soit le type de l'attribut demandé.
L'utilisation de ce paramètre est plus efficace que l'action par défaut (qui est de retourner tous les attributs ainsi que leurs valeurs associées). L'utilisation de ce paramètre doit toutefois être considéré comme une bonne pratique.
- attrsonly
-
Doit être défini à 1 si seuls les types des attributs sont demandés. S'il est défini à 0, les types et les valeurs des attributs sont récupérés, ce qui correspond au comportement par défaut.
- sizelimit
-
Vous permet de limiter le nombre d'entrées à récupérer. Le fait de définir ce paramètre à 0 signifie qu'il n'y aura aucune limite.
Note: Ce paramètre ne peut pas écraser la configuration côté serveur. Vous pouvez cependant positionner une valeur inférieure.
Quelques dossiers serveurs peuvent être configurés afin de ne retourner qu'un nombre d'entrées données. Si ce comportement survient, le serveur indique qu'il n'a retourné qu'un jeu de résultats partiel. Ce comportement intervient également si vous utilisez ce paramètre pour limiter le nombre d'entrées récupérées.
- timelimit
-
Définit le nombre maximal de secondes permis pour la recherche. Le fait de définir ce paramètre à 0 signifie qu'il n'y a pas de limite.
Note: Ce paramètre ne peut pas écraser la configuration côté serveur mais vous pouvez l'utiliser pour être plus restrictif.
- deref
-
Spécifie le nombre d'alias qui doivent être gérés pendant la recherche. Il peut être un parmi les suivants :
- LDAP_DEREF_NEVER - (défaut) les alias ne sont jamais déréférencés. dereferenced.
- LDAP_DEREF_SEARCHING - les alias doivent être déréférencés pendant la recherche mais pas lors de la localisation de l'objet de base de la recherche.
- LDAP_DEREF_FINDING - les alias doivent être déréférencés lors de la localisation de l'objet de base mais pas durant la recherche.
- LDAP_DEREF_ALWAYS - les alias doivent toujours être déréférencés.
Valeurs de retour
Retourne un identifiant de recherche ou FALSE si une erreur survient.
Historique
| Version | Description |
|---|---|
| 4.0.5 | Les recherches parallèles ont été ajoutées. Voir la fonction ldap_search() pour plus de détails. |
| 4.0.2 | Les paramètres attrsonly , sizelimit , timelimit et deref on été ajoutés. |
Exemples
L'exemple ci-dessous lit le nom du service, le nom, le prénom et l'email des employés de la société "Ma Compagnie", dont le nom ou le prénom contient la sous-chaîne : $person. Cet exemple illustre l'utilisation de filtres pour indiquer au serveur de faire une recherche sur deux attributs.
Exemple #1 Recherche LDAP
<?php
// $ds doit être une ressource de connexion valide
// $person est un nom ou une partie de nom (par exemple, "Jean")
$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";
?>
ldap_search
27-Aug-2008 02:17
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);
}
08-Aug-2007 01:18
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'"
25-Jun-2007 11:56
LDAP stuff is very nicely capsulated in the object oriented Net_LDAP class provided by PEAR:
http://pear.php.net/package/net_ldap
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.
<?php
// see: RFC2254
function ldap_quote($str) {
return str_replace(
array( '\\', ' ', '*', '(', ')' ),
array( '\\5c', '\\20', '\\2a', '\\28', '\\29' ),
$str
);
}
?>
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);
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";
$connection->Open();
$commande->ActiveConnection = $connection ;
$commande->Properties["Cache results"] = false;
// ACTIVATE PAGE MODE
$commande->Properties["Page size"] = 1000;
$recherche1 = "<LDAP://OU=XXXX,OU=Ressources_Locales,DC=COMMUN,
DC=AD,DC=YYYY,DC=FR>";
$recherche2 = ";(&(objectCategory=group)
(sIDHistory=*));distinguishedname;subtree";
$commande->commandtext = $recherche1.$recherche2;
$resultat = $commande->Execute();
$count = 0;
while (!$resultat->eof())
{
if ($count<10)
echo $resultat["distinguishedname"]."<br>";
$resultat->MoveNext();
$count = $count +1;
}
echo $count."<br>";
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:
<?php
//This code cannot be executed on the same server as AD is installed on!!!
//Connect
$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,"user@domain.com","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++)
{
echo $entries[$i]["displayname"][0]."<br />";
}
//never forget to unbind!
ldap_unbind($ad);
?>
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.
<?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;
?>
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 ";
?>
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:
<?
$r=ldap_search($ds,$base,$filter,array("createTimestamp"));
?>
01-Mar-2005 10: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
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.
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.
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.
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.
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.
<?
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
?>
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)");
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.
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.
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 = "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
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.": ".$info[$i][$data][$iii]."<br>";
}
}
echo "<p>"; // separate entries
11-Apr-2003 03: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);
?>
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...)', ...
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:
$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.
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.
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).
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.
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.
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
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:
http://www.microsoft.com/Exchange/en/55/help/documents/server/XOG16007.HTM
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:
http://www.cis.ohio-state.edu/htbin/rfc/rfc2254.html)
