How to get sAMAccountName from LDAP in Drupal
Posted on 23. Jun, 2011 by khumlo Freddie in Drupal
For all those Drupal developers who are working on intranet or similar websites and had LDAP module integrated so as to authenticate the users with their machine credentials, getting the real name of users has been a problem. Taking example of ‘Fernando Khumlo’ as the real name of the user with windows username as ‘f.khumlo’, real name is never stored in database from Drupal if authentication is done through LDAP and there is no seperate user profile content type. But we do really need this real name for many purposes. I will not list down where can it be applicable however I will explain how to get real user name from LDAP in Drupal.
In two ways, I have implemented to retrieve real user name – one on Drupal user edit page, you can set default value of user name’s text-field and two to set ‘Welcome f.khumlo’ as ‘Welcome Fernando Khumlo’ on page.tpl.php file of your drupal theme.
Set default value of a text field with login user name
- Go to Administer › Content Management
- Click on manage fields corresponding to your content type.
- Click on configure link to configure.
- Copy & paste below code snippet on the text area on PHP code under Default value container.
global $user; $ldap = unserialize($user->data); if(array_key_exists('ldap_dn', $ldap)){ $ldap_user = explode(',' , $ldap['ldap_dn']); $realname= explode('=', $ldap_user[0]); return array(0 => array('value' => $realname[1]),); }else{ return array(0 => array('value' => 'Admin'),); }
- Click on ‘save field settings’ button.
To set anywhere on the website
global $user; $ldap = unserialize($user->data); if(array_key_exists('ldap_dn', $ldap)){ $ldap_user = explode(',' , $ldap['ldap_dn']); $realname= explode('=', $ldap_user[0]); }else{ $realname[1] = 'Admin'; } print $realname[1];
On user table, there is a data field which stores LDAP query result in serialize format. So, we can unserialize the whole data present in data field which will output array key-value pair result. From there you can implement as you like to retrieve CN=”REAL NAME”. If there is no data in data field then we know it is the super admin unless we add users through Drupal register form.
Related Posts
- No related posts found




