LDAP Authentication using PHP

40,325

Solution 1

When you bind, you bind not to the username, but to DN.

Your $username variable should look like this:

$username = 'uid=testuser,ou=People,dc=domain,dc=com';

Solution 2

I guess ldap_connect() doesn't requires the protocol, so this naive patch should solve your issue:

--- ldap.php.bak    2012-09-04 10:52:29.563203493 +0200
+++ ldap.php    2012-09-04 10:52:46.807203766 +0200
@@ -1,6 +1,6 @@
 <?php

-$ldaphost = 'ldap://ldapServer';
+$ldaphost = 'ldapServer';
 $ldapport = 389;

 $ds = ldap_connect($ldaphost, $ldapport)

Check the basic example at the official documentation.

Share:
40,325
anujin
Author by

anujin

Updated on July 09, 2022

Comments

  • anujin
    anujin almost 2 years

    I am trying to use LDAP authentication using PHP.
    Below is my code:

    <?php
    
    $ldaphost = 'ldap://ldapServer';
    $ldapport = 389;
    
    $ds = ldap_connect($ldaphost, $ldapport)
    or die("Could not connect to $ldaphost");
        ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
    //ldap_set_option($ds, LDAP_OPT_DEBUG_LEVEL, 7);
    if ($ds) 
    {
        $username = "[email protected]";
        $upasswd = "testpass";
    
        $ldapbind = ldap_bind($ds, $username, $upasswd);
    
    
        if ($ldapbind) 
            {print "Congratulations! $username is authenticated.";}
        else 
            {print "Access Denied!";}
    
    
    }
    ?>
    

    But it raises the below error:

    PHP Warning: ldap_bind(): Unable to bind to server: Can't contact LDAP server

    Any idea as how can I get it resolved?

    Note: Do we need ldap.config file somewhere as I came across this term on some forum. I don't see any such file on my machine. I have php_ldap.dll in ext folder and using Windows.

  • westin
    westin over 11 years
    Actually, that depends on whether you're connecting to Microsoft Active Directory or any other LDAP directory. AD can handle Username + Domain/UPN (User Principle Name), but other LDAP directories requires (?) distinguished name.