ldap_bind

(PHP 3, PHP 4, PHP 5)

ldap_bind -- Bind to LDAP directory

Description

bool ldap_bind ( resource link_identifier [, string bind_rdn [, string bind_password]] )

Binds to the LDAP directory with specified RDN and password. Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.

Пример 1. Using LDAP Bind

<?php

// using ldap bind
$ldaprdn  = 'uname';    // ldap rdn or dn
$ldappass = 'password'// associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
   or die(
"Could not connect to LDAP server.");

if (
$ldapconn) {

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

  
// verify binding
  
if ($ldapbind) {
       echo
"LDAP bind successful...";
   } else {
       echo
"LDAP bind failed...";
   }
      
}

?>

Пример 2. Using LDAP Bind Anonymously

<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
   or die(
"Could not connect to LDAP server.");

if (
$ldapconn) {

  
// binding anonymously
  
$ldapbind = ldap_bind($ldapconn);

   if (
$ldapbind) {
       echo
"LDAP bind anonymous successful...";
   } else {
       echo
"LDAP bind anonymous failed...";
   }
 
}
  
?>


ldap_bind
romerom at cox dot net
12-Jul-2006 02:43
I ran into an issue trying to bind as "cn=manager,dc=example,dc=com".  I took the example kenn posted where he set LDAP_OPT_PROTOCOL_VERSION to "3" for the connection.  Once I set this, I was able to bind with my manager id.
dedlfix
03-May-2006 12:36
It doesn't make much sense to let die() the script in case of an error, otherwise to ask if there were no errors before proceeding the script, as the official examples do.

better:

<?php
ldap_bind
(...) or die(...);
do_something();
?>

or even better (die() is quick but dirty)

<?php
if (!ldap_bind(...)) {
 
error();
} else {
 
do_something();
}
?>
baroque at citromail dot hu
05-Nov-2005 01:18
This code sample shows how to connect and bind to eDirectory in PHP using LDAP for Netware.

<?php

$server
='137.65.138.159';
$admin='cn=admin,o=novell';
$passwd='novell';

$ds=ldap_connect($server);  // assuming the LDAP server is on this host

if ($ds) {
  
// bind with appropriate dn to give update access
  
$r=ldap_bind($ds, $admin, $passwd);
   if(!
$r) die("ldap_bind failed<br>");

   echo
"ldap_bind success";
  
ldap_close($ds);
} else {
   echo
"Unable to connect to LDAP server";
}
?>
17-Oct-2005 11:47
When using Active Directory 2003 (possibly also 2000) you can't search anonymously so you have to bind with a (known) user and password. Or else you will get an Search operations error. I also can confirm that an empty password bind succeeds! So test for an empty password first!

Some excellent information is found here:
http://www.scit.wlv.ac.uk/~jphb/sst/php/extra/ldap.html
http://www.scit.wlv.ac.uk/~jphb/sst/basics/ldap.html
darkstar_ae at hotmail dot com
15-Sep-2005 12:03
This may be a security issue but after tinkering for hours with the below ldap auth function (edi01 at gmx dot at), I discovered that the ldap_bind function will return true if you enter a valid username AND a NULL value!

so if that function were to receive something like $username = 'someuser' and $password = '', it would return true. As long as it isn't a null value the function will work as expected. Might as well check if it is null or empty then.
get_your_gun at hotmail dot com
23-Aug-2005 11:33
Hey

I was trying this all day and final noticed that when you use bind and authenticate. The user name needs to be as follows for it to work. I am using PHP V 4.03 so this might be different now but here is what I used and the auth worked.

<?php
$ldaphost
= "ldap.what.at.greatnet.com";
$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die(
"Could not connect to $ldaphost");

if (
$ds)
{
  
$username = "johndoe@what.at.greatnet.com";
  
$upasswd = "pass";

  
$ldapbind = ldap_bind($ds, $username, $upasswd);
                              
   if (
$ldapbind)
       {print
"Congratulations! $username is authenticated.";}
   else
       {print
"Nice try, kid. Better luck next time!";}
}

?>
edi01 at gmx dot at
05-Apr-2005 01:31
complete ldap authentication script:

function checkldapuser($username,$password,$ldap_server){
  if($connect=@ldap_connect($ldap_server)){ // if connected to ldap server

   if (ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3)) {
     echo "version 3<br>\n";
   } else {
     echo "version 2<br>\n";
   }
   echo "verification on '$ldap_server': ";

   // bind to ldap connection
   if(($bind=@ldap_bind($connect)) == false){
     print "bind:__FAILED__<br>\n";
     return false;
   }

   // search for user
   if (($res_id = ldap_search( $connect,
                               "dc=auto,dc=tuwien,dc=ac,dc=at",
                               "uid=$username")) == false) {
     print "failure: search in LDAP-tree failed<br>";
     return false;
   }

   if (ldap_count_entries($connect, $res_id) != 1) {
     print "failure: username $username found more than once<br>\n";
     return false;
   }

   if (( $entry_id = ldap_first_entry($connect, $res_id))== false) {
     print "failur: entry of searchresult couln't be fetched<br>\n";
     return false;
   }

   if (( $user_dn = ldap_get_dn($connect, $entry_id)) == false) {
     print "failure: user-dn coulnd't be fetched<br>\n";
     return false;
   }

   /* Authentifizierung des User */
   if (($link_id = ldap_bind($connect, $user_dn, $password)) == false) {
     print "failure: username, password didn't match: $user_dn<br>\n";
     return false;
   }

   return true;
   @ldap_close($connect);
  } else {                                  // no conection to ldap server
   echo "no connection to '$ldap_server'<br>\n";
  }

  echo "failed: ".ldap_error($connect)."<BR>\n";

  @ldap_close($connect);
  return(false);

}//end function checkldapuser

Here a sample for using this function:

if (checkldapuser('myuser', 'secretpassword', 'ldap://link.to.ldap')) {
  echo "ACCESS GRANTED\n";
} else {
  echo "ACCESS DENIED\n";
}
owen at delong dot com
24-Feb-2005 04:04
I am assuming that ldap_bind does a simple bind and that for other
types of bind, ldap_sasl_bind should be used.

Also, while the allow bind v2 solution will work with slapd, you really should
use ldap v3 if at all possible because of the security improvements and
better protocol definition.  LDAP v2 is largely deprecated at this point.

Hopefully the PHP default LDAP version will move to v3 soon.
phredbroughton at yahoo dot com
16-Feb-2005 11:27
As noted before with the password, I have found that if either  of the valuse for user or password are blank, or as in my case a typo resulted in a blank user as it was an undefined variable, the ldap_bind() will just perform an anonymous bind and return true!
Shouldn't this detect the presence of the additional values and return an error? At least if the user or password is passed. If they are both blank I'm not sure what it should do.
wkaiser at mpimf-heidelberg dot mpg dot de
24-Nov-2004 11:40
If you do not want to bind as unixadmin or *manager (i. e., for authentication on web applications), the following code could be useful:
<?php

$ldaphost
= "ldap.yourdomain.com";

/*for a SSL secured ldap_connect()

$ldaphost = "ldap.yourdomain.com"; */

$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die(
"Could not connect to $ldaphost");

if (
$ds) {

$username = "some_user";
$upasswd = "secret";
$binddn = "uid=$username,ou=people,dc=yourdomain,dc=com";

$ldapbind = ldap_bind($ds, $binddn, $upasswd);
                          
if (
$ldapbind) {

print
"Congratulations! $some_user is authenticated.";}

else {

print
"Nice try, kid. Better luck next time!";}}

?>
jakob at grimstveit dot no
19-Oct-2004 08:33
As "john dot lewis at waldenweb dot com" correctly writes (and this is important to note and SHOULD be incorporated into the documentation as a warning - trying to bind with specific username and empty password will return TRUE.
kenn at pcintelligent dot com
13-Jun-2004 11:32
I want to point out that the line that reads

"$ldaprdn  = 'uname';" 

is a bit confusing. You need to ensure that you use the entire rootdn. for instance. your code should look more like this...

<?php

// using ldap bind *** NOTE the uname *****
$ldaprdn  = 'cn=root,dc=testserver,dc=com';    // ldap rdn or dn
$ldappass = 'secret'// associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.testserver.com")
   or die(
"Could not connect to LDAP server.");

if (
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
   echo
"Using LDAPv3";
} else {
   echo
"Failed to set protocol version to 3";
}

if (
$ldapconn) {

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

  
// verify binding
  
if ($ldapbind) {
       echo
"LDAP bind successful...";
   } else {
       echo
"LDAP bind failed...";
   }

}

?>
pete dot rowley at example dot com
31-Dec-2003 08:51
You should NOT attempt to bind with a made up password.  However small the chance, the chance remains that your code produces a valid password.  The correct behaviour is to test for an empty password, and if your application will only service authenticated users, not perform any more LDAP operations on behalf of the user - this also happens to be more efficient.
kokheng at jhs dot com dot sg
21-Nov-2002 01:01
OpenLdap 2.1.x libraries support both LDAPv2 and LDAPv3. The problem lies with the slapd, the ldap server bundled with OpenLDAP.  It's default supported version is LDAPv3. One can set the "allow bind_v2" in the slapd.conf file, with this configured, the PHP ldap_set_option() is not required.
elvisciousatrmci.net
27-Sep-2002 11:08
I ran into a problem where I was getting a protocol error when I tried to bind.  I was able to connect fine and ldap commands worked fine from the command line. 

The problem turned out to be that openldap (v 2.1.5) was starting up in version 3 ldap mode, and php (4.2.3) expected it to be in version 2 mode.

To fix this use the ldap_set_option command to change the version that php expects.
naujocke at nospam dot abacusii dot com
06-May-2002 09:27
One useful item when trying to bind to Novell's NDS LDAP servers.

If you are using NDS 8 and attempt to bind it will work with a partail context.

As an example if you full context is cn=user.ou=sales.ou=division.o=company
and you use as your authentication context cn=user.o=company it will work.

But you will be required to supply the full context to authenticate to an eDirectory based LDAP setup. Such as Netware 6 or eDirectory 8.5 or greater.

Also when using the wildcard * symbol in your object class. If you are not careful it is possible to dump the entire contents of your NDS tree into an array.
tpiper at pinnacle dot couk
26-Feb-2002 07:19
An example to help you authenticate against M$ Exchange, rather than use anonymous mode...

you will need to create an NT domain member (I've called it ldapquery) and give it search permission in the LDAP protocol settings in Exchange.

then:
$ds=ldap_connect ("<exchange server>"); 
$r=@ldap_bind($ds,"cn=ldapquery, o=<your organisation>, c=<your country>, ","<the password for ldapquery account>");

we've tested this on Exchange 5.5SP3.
ral at royal dot net
21-Jul-2001 10:49
I'm using the following code to generate
'userPassword' for OpenLDAP 1.2.x using {ssha} method
(to encrypt {smd5} just change MHASH_SHA1 to MHASH_MD5)

  mt_srand((double) microtime()*1000000);
  $salt=mhash_keygen_s2k(MHASH_SHA1,$password,substr(pack("h*",md5(mt_rand())),0,8),4);
  $passsword="{ssha}".base64_encode(mhash(MHASH_SHA1, $password.$salt).$salt);
ian-php at eiloart dot com
06-Jun-2001 05:16
You might also get the message "Inappropriate authentication" when your username/password pair is invalid.
gparamelle at ina dot fr
10-Nov-2000 06:00
if you use ldap_bind() to test an aurhentification, it will return something like "Warning: LDAP: Unable to bind to server: Invalid credentials in
test.php on line 50"
to avoid this use error_reporting (E_ALL & ~E_NOTICE & ~E_WARNING)
or better solution :
@ldap_bind($ds, $dn, $password) ;
pelle at alma dot nu
03-Aug-2000 11:27
Regarding "invalid credentials",
according to the rfc
"Invalid credentials" is the LDAP
response code returned when password/username pair isnt correct.
john dot lewis at waldenweb dot com
14-Dec-1999 05:01
To get around the null password returns true on servers where anonymous access is allowed, try...

// get a connection
       $ldap=ldap_connect($ldapServer);
// check to see if we got one, if we did, proceed
       if($ldap)
       {
               if(!$passWord)
               {
       // generate a bogus password to pass if the user doesn't give us one
     // this gets around systems that are anonymous search enabled
                   $passWord = crypt(microtime());
               }

then do your ldap_bind to test authentication....

<ldap_addldap_close>
 Last updated: Tue, 15 Nov 2005