PHP LDAP Multiple Binds
<p>Quite new to PHP and LDAP here, looking for some assistance with a personal project (trying to teach myself!).</p>

<p>I would like to password protect certain pages on our website using a simple login box. </p>

<p>My <strong>login.php</strong> page contains a simple login form with <em>username</em> and <em>password</em> inputs. I have managed to get the login process working using the code below. I am able to use my Active Directory username/pass to login via this form and proceed to the desired page, no issues.</p>

<p>However I'm not sure if I am doing it the 'correct' way. </p>

<p>My code;</p>

<p><strong>ldap.php</strong></p>

<pre><code>session_start();

function authenticate($user, $password) {
    if(empty($user) || empty($password)) return false;
    $ldaphost = "ad.example.com"; 
    $ldap_dn = "DC=ad,DC=example,DC=com"; 
    $ldap_user_group = "Staff"; 
    $ldap_usr_dom = '@ad.example.com'; 
    $ldap = ldap_connect($ldaphost);

    if($bind = ldap_bind($ldap, $user.$ldap_usr_dom, $password) or die ("Error: ".ldap_error($ldap))) {
        $filter = "(sAMAccountName=".$user.")";
        $attr = array("");
        $result = ldap_search($ldap, $ldap_dn, $filter) or exit("Unable to search LDAP server") or die ("Error searching: ".ldap_error($ldap));
        $entries = ldap_get_entries($ldap, $result);
        ldap_unbind($ldap); 
    }   

    foreach($entries[0]['memberof'] as $grps) {
        if(empty($grps) || empty($ldap_user_group)) return false;
        if(strpos($grps, $ldap_user_group)) {
            $access = 1;
        } else {
        }
    }

    if($access != 0) {
            $_SESSION['user'] = $user;
            $_SESSION['access'] = $access;
            return true;
        }  else {
        return false;
    }
}
</code></pre>

<p>I've been told (by someone else) that this particular LDAP authentication process should work in two steps, as follows;</p>

<ul>
<li><em>A search is made for the entered user name. I would recommend you use a search user DN and password for this – a user that has search permissions. It binds with these credentials before making the search. If the search succeeds it retrieves the DN of the found user and the search attribute which will later be used to look up the member record</em>. </li>
<li><em>A second bind is then made with the retrieved user DN and the entered password. If this bind succeeds then the user is authenticated.</em></li>
</ul>

<p>My questions are;</p>

<ul>
<li>Is the above statement correct? </li>
<li>Are two 'binds' necessary? </li>
<li>Can't I just bind the LDAP connection with the credentials the user entered?</li>
</ul>

<p>Any advice is appreciated, I'm struggling to get my head round the authentication process really :s</p>