<?php
$realm = "MY REALM HERE";
$ldaphost = "my.ldap.host";
$ldaptls = "yes";
$ldapbase = "dc=my,dc=server,dc=com";
$checkuser = "cn";
function basicAuth() {
global $realm;
header('WWW-Authenticate: Basic realm="'.$realm.'"');
header('HTTP/1.0 401 Unauthorized');
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER'])) {
basicAuth();
} else {
$tstusername = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
$ldapconn = ldap_connect($ldaphost, 389)
or error_die("connection to LDAP host failed");
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3)
or error_die("failed to set LDAP protocol version 3");
if ($ldaptls!="no" & & $ldaptls!=0 & & $ldaptlS)
ldap_start_tls($ldapconn)
or error_die($ldapconn, "cannot start LDAP TLS");
if ($ldapbind = @ldap_bind($ldapconn, $checkuser.'='.$tstusername.','.$ldapbase, $password)) {
$search = ldap_search($ldapconn, $ldapbase, $checkuser.'='.$tstusername, array('mail\
', 'cn'));
$data = ldap_get_entries($ldapconn, $search);
ldap_close($ldapconn);
$username = $tstusername;
$email = array('count' => 1, 0 => $username.'@'.$_SERVER[HTTP_HOST]);
$fullname = $username;
if ($data['count']==1) {
if (isset($data[0]['mail']))
$email = $data[0]['mail'];
if (isset($data[0]['cn'][0]))
$fullname = $data[0]['cn'][0];
}
} else {
error_log("user login failed: ".$checkuser.'='.$tstusername.','.$ldapbase);
error_log(ldap_error($ldapconn));
ldap_close($ldapconn);
basicAuth();
}
}
?>