Search code examples
phpldapldap-query

How to perform LDAP bind given email and password in PHP?


I am working on application that uses LDAP for authentication. Currently I can authenticate users using uid and password. I'm testing with the online LDAP test server ( http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/#comment-5882)

This is my code:

<?php
$ldapConn = ldap_connect('ldap.forumsys.com');

ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);

//sample path for authentication
ldap_bind($ldapConn, 'uid=riemann,dc=example,dc=com', 'password');

//example path for searching
$search = ldap_search($ldapConn, "uid=riemann,dc=example,dc=com", "(cn=*)");
$searchData = ldap_get_entries($ldapConn, $search);

print_r($searchData);

The code searches users and authenticates them using uid attribute but now I want to authenticate users given their e-mail address.


Solution

  • At first : credit goes to @Zoran Regvart. the problem was there are only 4 parameters in ldap_search() function,check the $entries['count'] > 0

    $ldapConn = ldap_connect('ldap.forumsys.com');
    ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
    $password='password';
    $mail = 'riemann@ldap.forumsys.com';
    if(ldap_bind($ldapConn, 'cn=read-only-admin,dc=example,dc=com', 'password')) {
    
                $arr = array('dn', 1);
                $result = ldap_search($ldapConn, 'dc=example,dc=com', "(mail=$mail)", $arr);
                $entries = ldap_get_entries($ldapConn, $result);
                    echo "<br><hr>";
                    print_r($entries);
                if ($entries['count'] > 0) {
                    if (ldap_bind($ldapConn, $entries[0]['dn'], $password)) {
                        // user with mail $mail is checked with password $password
                        echo 'user auth success';
                    }else{
                        echo 'user auth failed';
                    }
                }
    
            }
    ldap_close($ldapConn);