Luis G. Lino
Luis G. Lino

Reputation: 163

Get user's name from LDAP PHP

I need to retrieve my user's name to set a variable and use it to have a better welcome to the user.

Example: Login with luis.lino and it set $name = "Luis Lino" where Luis Lino is retrieved from AD through LDAP.

As so I can do "Welcome Luis Lino, we hope you enjoy your time in here"

I am using this code:

$myusername = mysqli_real_escape_string($db,$_POST['username']) . "@domain.com";
        $mypassword = mysqli_real_escape_string($db,$_POST['password']); 
        $local = $_POST['filial'];
        $ldap = ldap_connect("ldap://domain.com");
        if ($bind = ldap_bind($ldap, $myusername, $mypassword)) 
        {
            $_SESSION['login_user'] = $myusername;
            $filter = "(&(sAMAccountName={$myusername}))";
            $ldap_dn = "dc=domain.com";
            $attr = array("givenname");
            $result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("Unable to search LDAP server");
            $entries = ldap_get_entries($ldap, $result);
            $givenname = $entries[0]['givenname'][0];
            ldap_unbind($ldap);

            setcookie("name", $givenname, time() + (86400 * 30), "/");  

            setcookie("sessao", $local, time() + (86400 * 30), "/"); // 86400 = 1 dia
            header("location: welcome.php");
        } 

If I just use the "login" part it works perfectly, but with the above code I get the following error:

Warning: ldap_search(): Search: Client Loop in C:\wamp\www\OperPHP\index.php on line 20

I already looked into lots of posts but none solved my problem, anyone know how to solve this?

Upvotes: 1

Views: 2998

Answers (1)

ChadSikorra
ChadSikorra

Reputation: 2869

I would try changing the following for connecting to LDAP (just need the additions below ldap_connect():

$ldap = ldap_connect("ldap://domain.com");
// Set to LDAPv3 protocol, disable referrals...
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

Based on the error you're getting, it seems like it's stuck trying to do a referral. Also, your filter could be simplified to $filter = "(sAMAccountName={$myusername})";. I'm also not sure if this is just due to the example you're giving, but typically you want the base DN ($ldap_dn in your case) to be like this: $ldap_dn = "dc=domain,dc=com";.

Upvotes: 1

Related Questions