Skip to content

Instantly share code, notes, and snippets.

@kirkegaard
Created February 16, 2015 22:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirkegaard/ac28d2b8e77861d380d5 to your computer and use it in GitHub Desktop.
Save kirkegaard/ac28d2b8e77861d380d5 to your computer and use it in GitHub Desktop.
Check if user exists in one or more groups in Apple ldap tree
<?php
$ldapuser = 'user';
$ldappass = 'pass';
// Required groups
$groups = array('cn=group1', 'cn=group2');
// Ldap stuff
$directory = 'directory.example.dk';
$dc = 'dc=directory,dc=example,dc=dk';
$ldaprdn = 'uid=' . $ldapuser . ',cn=users,' . $dc;
$ldapgdn = 'cn=groups,' . $dc;
// connect to ldap server
$ldapconn = ldap_connect($directory)
or die("Could not connect to LDAP server.");
ldap_set_option( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
if ($ldapconn) {
// binding to ldap server
// @ because we dont need the warning error
$ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);
// Verify binding or die fast
if (!$ldapbind) {
print "LDAP bind failed...\n";
exit;
}
// The user exists in the user tree. Now we need to find the groups he's in
print "LDAP bind successful...\n";
// Fetch the users of the required groups
$query = ldap_search($ldapconn, $ldapgdn, '(|(' . implode($groups, ')(') . '))', array('cn', 'memberuid'));
// Read all results from search
$data = ldap_get_entries($ldapconn, $query);
// Lets see if user is inside any of the required groups
$user_groups = array();
for ($i=0; $i < $data['count']; $i++) {
if(in_array($ldapuser, $data[$i]['memberuid'])) {
$user_groups[] = $data[$i]['cn'][0];
}
}
// Did we find one or more?
if($user_groups) {
print "Found user in groups: " . implode($user_groups, ', ') . "\n";
} else {
print "Didnt find user in any of the required groups\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment