How can i get manager name from AD in php? - php

Now, i'm doing to connect my website to AD use ldap and get data from user logon but my problem is when user logon and i need to get manager name of user i get manager name by call $entries[0]["manager"][0] it's show data like this CN=rosie,OU=AllUser,DC=xyz,DC=local i need to get only manager name that is 'rosie' but i don't know to get it, please help
this my code
$ldap_host ="servername";
$ldap_port = "port";
$ldap_dn = "OU=AllUser,DC=abc,DC=local";
$ldap_usr_dom = '#abc.local';
$ldap_it_group = "IT";
$ldap = ldap_connect($ldap_host,$ldap_port) or die("Could not connect to ".$ldap_host);
$bind = #ldap_bind($ldap, $user.$ldap_usr_dom, $password) or die("cant bind");
if($bind) {
$filter = "(&(objectClass=*)(sAMAccountName=".$user."))";
$attr = array("manager");
$result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap, $result);
ldap_unbind($ldap);
for ($i=0; $i<$entries["count"]; $i++) {
echo "Manager is: ". $entries[0]["manager"][0]."<p>";
}

This method is a totally horrible way of doing it... doing regex would be better, but this is a quick hack job for ya, until the regex guys come around to provide the expression.
$manager = str_replace('CN=','',strstr($entries[0]["manager"][0],',',true));
echo "Manager is: ". $manager ."<p>";

Related

PHP - LDAP Authentication and Search

I am using an Online LDAP Test Server here: http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/ to test some basic LDAP code.
I need to authenticate a user and retrieve some user information.
If I understand the information about the test server correctly I should be able to bind with users that belong to respective groups. With the code 'AS IS' below I can bind to un-commented $dn, but if I use any other $dn to authenticate, the bind fails.
What am I not understanding?
For example, tesla should belong to 'ou=scientists,dc=example,dc=com' but I am unable to authenticate tesla on that DN and subsequently I can't search for related information.
$dn = 'dc=example,dc=com';
// $dn = 'ou=mathematicians,dc=example,dc=com';
// $dn = 'ou=scientists,dc=example,dc=com';
$username = 'tesla';
$password = 'password';
$filter = "(uid=" . $username . ")";
$ldapDN = 'uid=' . $username . ',' . $dn;
$ldapCONN = ldap_connect("ldap.forumsys.com") or die("Could not connect to LDAP server.");
if ($ldapCONN)
{
ldap_set_option($ldapCONN, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldapBIND = #ldap_bind($ldapCONN, $ldapDN, $password);
if ( $ldapBIND )
{
$result = ldap_search($ldapCONN, $dn, $filter) or die ("Error: ".ldap_error($ldapCONN));
$data = ldap_get_entries($ldapCONN, $result);
echo '<pre>';
print_r($data);
echo '</pre>';
}
else
{
echo "LDAP bind failed...";
}
}
When using LDAP, it is important to visualize how the database is organized.
Basically, all users are in the main folder. Use this folder to authenticate your user with, otherwise it will not work.
In this case the main folder where all users are in, is dc=example,dc=com. However, most LDAP servers use a main folder like cn=users,dc=example,dc=com.
Why are they using folders at all then? Well, that is to make it easier to categorize and search with a filter. For example, if you want to only show the names of scientists, you add the group Scientists to your search filter like $filter = "(ou=Scientists)". A filter for both groups would look like this: $filter = "(&(ou=Scientists)(ou=Mathematicians)". Now the server will take a look into this folder/these folders, and display just these members.
Hope this helps, for gaining further insight in how the server is organized, I can recommend installing Apache Directory Studio. It is free to download from their site, helped me a lot!

Getting user readable name via LDAP with PHP by having only the login credentials

I am integrating my login form with Microsoft active directory. I authenticate
users via LDAP php library.
When user try to log in, they enter username & password.
Connecting to server go successfully, authentication via "LDAP_bind" also
give me true or false according to the values correctness.
Now i am not able to retrieve the user Real name to display it on the screen.
ALL Information I have are the ldap uri with the port number, and username & password entered via the webform.
here is my current code,
$ldap = ldap_connect("ldap://abc.xyz:123");
if ($bind = ldap_bind($ldap, $_REQUEST['username'].'#abc.xyz',$_REQUEST['password']))
{ echo "Welcome". $_REQUEST['username'];}
the $_REQUEST['username'] is not human readable, so i need to read this user attributes or at least display name only.
ldap_search and ldap_read functions did not help, I tried this code:
$ldap_base_dn = 'DC=abc,DC=xyz';
$search_filter = "(objectclass=*)";
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter);
with no luck, is there any other information i must have in order to make the ldap_search or ldap_read work successfully. in other words can this be done by having the username and password and the ldap uri only?
You should be able to do the search like this:
$upn = $_REQUEST['username'].'#abc.xyz';
$attributes = ['displayname'];
$filter = "(&(objectClass=user)(objectCategory=person)(userPrincipalName=".ldap_escape($upn, null, LDAP_ESCAPE_FILTER)."))";
$baseDn = "DC=abc,DC=xyz";
$results = ldap_search($ldap, $baseDn, $filter, $attributes);
$info = ldap_get_entries($ldap, $results);
// This is what you're looking for...
var_dump($info[0]['displayname'][0]);
Also, make sure to do the bind with these options:
$ldap = ldap_connect("ldap://abc.xyz:123");
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
if ($bind = ldap_bind($ldap, $_REQUEST['username'].'#abc.xyz',$_REQUEST['password']))
When returning the DisplayName value, I recommend that you use a search filter which looks for the samaccountname (username) using something as simple as (samaccountname=$u) with $u being the username from your LDAP connect. If your Active Directory/Open Directory has a lot of objects, I would most certainly recommend targeting OU's as this query can fall on it's bottom pretty quickly.
I've made some further changes to your code so it now runs inside a function which takes 3x params and returns false if the connection or authentication fails.
Check LDAP - Return DisplayName if success login or FALSE(BOOL) if fail login or connection.
function chkLDAP($u, $pass, $domain) {
$dom = "$domain\\"; //Domain Prefix for UNAME which ouputs "domain\"
$user = $dom . $u;
$hostname = 'ldap://abc.com';
$baseDN = 'OU=users, DC=abc, DC=com'; //Narrow down if you have alot of objects as search could take along time
$search = "(samaccountname=$u)"; //Compare with Username
$ldap = ldap_connect($hostname);
if ($ldap) {
$ldapbind = ldap_bind($ldap, $user, $pass);
if ($ldapbind) {
$ldapSearch = ldap_search($ldap, $baseDN, $search);
$entry = ldap_first_entry($ldap, $ldapSearch);
$info = ldap_get_values($ldap, $entry, "displayname");
return $info[0];
}
return false; //Failed Auth
}
return false; //Connection Failed
}
Just test the function for false to make sure you have a displayname before using it.
Run Function:
$displayName = chkLDAP($_REQUEST['username'], $_REQUEST['password'], 'abc.com'); //Run Function - Returns False if Failed or Displayname if True
if ($displayName !== false) {
echo $displayName;
} else {
echo "Username or Password Incorrect!";
}
See:
http://php.net/manual/en/function.ldap-get-values.php
This worked for me for people who need to validate if a user exists in a specific OU.
(by the help of #kitson88 response)
function validateLogin($username,$password)
{
$ldap_dn = "$username#alhait.com";
$ldap_password =$password;
$ldap_con = ldap_connect("server");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
if(#ldap_bind($ldap_con,$ldap_dn,$ldap_password))
{
$baseDN = 'OU=trainers,DC=alhait,DC=com';
$search = "(samaccountname=$username)";
$ldapSearch = ldap_search($ldap_con, $baseDN, $search);
$entry = ldap_first_entry($ldap_con, $ldapSearch);
$info = ldap_get_values($ldap_con, $entry, "displayname");
// var_dump($info[0]);
if($info[0]!=null)
{
return true;
}
}else{
return false;
}
//echo "Invalid Credential";
return false;
}

Single Sign On with Active Directory Using LDAP

I am trying to get user information from LDAP function. I need a single sign in for my PHP application on Active Directory. I am using following function:
$ldapserver = 'abc.com';
$ldapuser = 'ali#abc.com';
$ldappass = 'xyz';
$attributes_ad = array
("displayName","description","cn","givenName","sn","mail","co","mobile","company","
displayName");
// define base
$base ="";
// connect
$ldapconn = ldap_connect($ldapserver) or die("Could not connect to LDAP server.");
if($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to
bind: ".ldap_error($ldapconn));
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...<br /><br />";
$result = ldap_search($ldapconn, $base, "mail=$email*", $attributes_ad) or die ("Error in search
query");
$info = ldap_get_entries($ldapconn, $result);
//Now, to display the results we want:
for ($i=0; $i<$info["count"]; $i++)
{
// to show the attribute displayName (note the case!)
echo $info[$i]["displayname"][0];
}
}
}
Above code requires username and password both but I need a solution that can get the username and password whenever someone will login with AD credentials I need to use them to authenticate my login for my PHP application (actually it is an intranet application). Please help me with that I need to fetch all available user info from active directory.

PHP ldap_list() Bad search filter

I'm trying to list my Active Directory users using PHP ldap_list() function. I get the following errors when I execute the php code.
LDAP bind successful... Warning: ldap_list(): Search: Bad search filter in /var/www/html/ldapn.php on line 29
Below is my PHP Code:
<?php
// using ldap bind
$ldaprdn = 'draven#myserver.com'; // ldap rdn or dn
$ldappass = 'draven678'; // associated password
// connect to ldap server
$ldapconn = ldap_connect("dc.myserver.com")
or die("Could not connect to LDAP server.");
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}
$basedn = "dc=myserver, dc=com";
$justthese = array("OU_Test");
$sr = ldap_list($ldapconn, $basedn, "OU_Test=*", $justthese);
}
?>
note : OU_Test is an Organizational unit. My requirement is to list all users in that Organizational Unit.
What's wrong with my code? How will I be able to resolve this error?
To list all users in the Organizational Unit 'OU_TEST' with ldap_list() :
Use the appropriate $basedn. It should be the distinguished name of 'OU_TEST' since you want to list users that are INSIDE OU_TEST. You can get it with ldap_search().
Use the appropriate filter : to list only users, filter by users.
// 1. Get OU_TEST's dn. Search down the tree using a top/root dn as $basedn :
$basedn = "dc=myserver, dc=com";
// Filters usually looks like ([attributeName]=[attributeValue])
$filter = '(ou=OU_TEST)';
$sr = ldap_search($ds, $basedn, $filter);
... say we put the resulting dn in $OU_TEST_dn variable...
// 2. List users. If users are missing, use 'objectClass=organizationalPerson'
$filter = '(objectClass=Users)';
// Use the correct basedn
$basedn = $OU_TEST_dn;
// This should work
$sr = ldap_list($ldapconn, $basedn, $filter);
the filter here should be in braces:
here is how:
$sr = ldap_list($ldapconn, $basedn, "(OU_Test=*)", $justthese);
This should work just fine.
If it doesn't work
follow the example here
<?php
$ldapconfig['host'] = '10.10.10.10';
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=company,dc=com';
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);
$dn="uid=".$username.",ou=OU_TEST,".$ldapconfig['basedn'];
if ($bind=ldap_bind($ds, $dn, $password)) {
echo("Login correct");
} else {
echo("Unable to bind to server.</br>");
echo("msg:'".ldap_error($ds)."'</br>"); //check if the message isn't: Can't contact LDAP server :)
//if it say something about a cn or user then you are trying with the wrong $dn pattern i found this by looking at OpenLDAP source code :)
//we can figure out the right pattern by searching the user tree
//remember to turn on the anonymous search on the ldap server
if ($bind=ldap_bind($ds)) {
$filter = "(OU_TEST=*)";
if (!($search=#ldap_search($ds, $ldapconfig['basedn'], $filter))) {
echo("Unable to search ldap server<br>");
echo("msg:'".ldap_error($ds)."'</br>"); //check the message again
} else {
$number_returned = ldap_count_entries($ds,$search);
$info = ldap_get_entries($ds, $search);
echo "The number of entries returned is ". $number_returned."<p>";
for ($i=0; $i<$info["count"]; $i++) {
var_dump($info[$i]); //look for your user account in this pile of junk and apply the whole pattern where you build $dn to match exactly the ldap tree entry
}
}
} else {
echo("Unable to bind anonymously<br>");
echo("msg:".ldap_error($ds)."<br>");
}
}
?>
Let me know if it does not work. We will try and figure it out!

LDAP - List groups

I need to list all groups within a certain group using PHP. This is what I have so far:
<?php
$ldap_dn = "ou=People,dc=something,dc=something,dc=something,dc=au";
$ldap_svr = "ldap.server.somewhere";
$ldap_domain = "domain.somewhere";
$conn=ldap_connect($ldap_svr) or die("Cannot connect to LDAP server!");
ldap_set_option ($conn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($conn,"user#domain.somewhere","password");
$filter ="(ou=*)";
$justthese = array("ou");
$result=ldap_list($conn, $ldap_dn, $filter, $justthese) or die("No search data found.");
$info = ldap_get_entries($conn, $result);
for ($i=0; $i < $info["count"]; $i++) {
echo $info[$i]["ou"][0] . '<br />';
}
?>
This returns a list of groups, one of whch is 'Students', but I want to list all groups within 'Students'. How can I do this?
EDIT
Thanks to Fluffeh the Microsoft LDAP plugin allows me to search active directorys so I can tailor my PHP script accordingly, e.g. $ldap_dn = "ou=Units,ou=Groups,dc=somewhere,dc=somewher,dc=somewhere,dc=au";
So my mostly working code is:
<?php
$ldap_dn = "ou=Units,ou=Groups,dc=somewhere,dc=somewher,dc=somewhere,dc=au";
$ldap_svr = "ldap.server.somewhere";
$ldap_domain = "domain.somewhere";
$conn=ldap_connect($ldap_svr) or die("Cannot connect to LDAP server!");
ldap_set_option ($conn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($conn,"user#domain.somewhere","password");
$filter ="(cn=*)";
$justthese = array('cn');
$result=ldap_list($conn, $ldap_dn, $filter, $justthese) or die("No search data found.");
$info = ldap_get_entries($conn, $result);
for ($i=0; $i < $info["count"]; $i++) {
echo $info[$i]["cn"][0] . '<br />';
}
?>
You need to actually pass the search to it. Currently you are using:
$filter ="(ou=*)";
This will need to change to contain 'Students'. While I am no LDAP expert, I would guess at the following:
$filter ="(cn=Students)";
Most of the LDAP stuff I have done has been sheer trial and error rather than knowing what I am doing, but this might put you on the right path.
There is also a Microsoft plugin - Active Directory Explorer you can use to at least browse the LDAP so that you know what to search for and under what branch.

Categories