<?php
$SEARCHDN 
"";
$UID="uid";
$LDAPHOST "ldap://ldap.nabber.org";

function 
ldap_login($uid$password) {
  
$dn search($uid);
  return 
bind($dn$password);
}

function 
bind($uid$password) {
  
//return FALSE on failure, user list otherwise
  
global $UID;
  global 
$LDAPHOST;
  global 
$SEARCHDN;

  
$filter $UID "=$uid";

  
$ds=ldap_connect($LDAPHOST);

  if (
$ds) {
     
set_v3($ds);

     
// bind with appropriate dn to give update access
     //anonymous bind
     
$r=@ldap_bind($ds$uid$password);

     
// verify binding
     
if ($r) {
         
//echo "<p>LDAP bind successful...</p>";
         
return TRUE;
     } else {
         
//echo "<p>LDAP bind failed.</p>";
         
return FALSE;
     }

  } else {
     
//echo "<p>Unable to connect to LDAP server: $host</p>";
     
return FALSE;
  }
  return 
FALSE;
}


function 
search($uid) {
  
//return FALSE on failure, user list otherwise
  
global $UID;
  global 
$LDAPHOST;
  global 
$SEARCHDN;

  
$filter $UID "=$uid";
  
$attr = array("dn");

  
$ds=ldap_connect($LDAPHOST);

  if (
$ds) {
     
set_v3($ds);

     
// bind with appropriate dn to give update access
     //anonymous bind
     
$r=@ldap_bind($ds);

     
// search directory data
     
$r ldap_search($ds$SEARCHDN$filter$attr);

     
$entries ldap_get_entries($ds$r);

     
ldap_close($ds);
     return 
$entries[0]['dn'];

  } else {
     
//echo "<p>Unable to connect to LDAP server: $host</p>";
     
return FALSE;
  }
}


function 
set_v3($ds) {
     
//bugfix, must set protocol manually
     
$result ldap_set_option($dsLDAP_OPT_PROTOCOL_VERSION3);
/*
     if ($result) {
       echo "<p>LDAP version 3</p>\n";
     } else {
       echo "<p>LDAP version 2</p>\n";
     }
*/
   
if (!ldap_start_tls($ds)) {
       
//print "<p>Ldap_start_tls failed</p>";
   
}
   return 
$result;
}

?>