title: Active Directory Validation is Slow in PHP
body: <p>So I'm validating username, password, and group membership in active directory like so:</p>
  <pre><code>function validate($username, $password, $groupname = null) {
    if ($username &amp;&amp; $password) {
      $link = ldap_connect($domain);
      if ($link) {
        ldap_set_option($link, LDAP_OPT_PROTOCOL_VERSION, 3);
        $bind = ldap_bind($link, $username, $password);
        if ($bind) {
          if ($groupname) {
            $filter  = &quot;(samAccountName=&quot;.$username.&quot;)&quot;;
            $attrs   = array(&quot;memberOf&quot;);
            $res     = ldap_search($link, $baseDN, $filter, $attrs);
            $entries = ldap_get_entries($link, $res);
            $isMember = false;
            if ($entries &amp;&amp; $entries[0] &amp;&amp; $entries[0]['memberof']) {
              $arr = $entries[0]['memberof'];
              foreach ($arr as $key =&gt; $value) {
                if ($key != 'count') {
                  $isMember = $isMember || preg_match(&quot;|&quot;.preg_quote($groupname).&quot;|&quot;, $value);
                }
              }
            }
            return $isMember;
          } else {
            return true;
          }
        } else {
          return false;
        }
      } else {
        error_log(&quot;Could not connect to Active Directory&quot;);
        return false;
      }
    } else {
      error_log(&quot;Username or password missing&quot;);
      return false;
    }
  }
  </code></pre>
  <p>This works correctly, but is <em>painfully</em> slow, taking as much as 2~3 minutes to validate that a user is a member of a group.. If I omit the group membership check it runs almost instantaneously. How can I speed this up (without caching)?</p>
  <h1>EDIT</h1>
  <p>since it was not clear from the question, the bottle neck is the <code>ldap_search</code> function which takes ~127 seconds, rest of the program runs in less than a second. Should also add that we only have about 20 AD users and 10ish groups.</p>