Connect to Active Directory LDAP with PHP
Today we are going to see how to make an authentication with PHP and an Active Directory LDAP (AD).
This code sample has been tested on a Windows 2k3 server.
First time, your server need the LDAP standard connection on the port 389, it’s activate for a default creation of the AD.
Your LAMP / WAMP server also need the php_ldap extension.
I’m using the PHP features to make a connection and the authentication.
First step, make the connection to the AD server :
$host = "my.server.host.com"; //Get authentication information by login form $myLogin = $_POST["loginAD"]; $myPass = $_POST["passAD"]; $ressource = ldap_connect($host);
PHP will connect to server on the port 389, then you have to authenticate with an AD user to access to his information.
if($ressource){ try{ //Authentication to the AD with a windows login, password $bind = ldap_bind($ressource, $myLogin."@".$host, $myPass); /** **To get all information, its necessary to be logged. **It exists an anonymous mode, if you want to test only the server connection **Now we can get all information about this user */ //$dn contain information asked by Windows server to browse the correct AD tree. //Here I want to browse all Users in the LDAP AD $dn = "CN=Users,DC=my,DC=server, DC=host,DC=com"; /*I search email, groups and the name of the user *We can have many information about a user, *you can see all of them with removing the last argument in the ldap_search */ $result = ldap_search($ressource, $dn, "samaccountname=".$myLogin, array("mail", "memberof","name")); //ldap_get_entries will return an array of all asked information $info = ldap_get_entries($ressource, $result); echo " <pre>".print_r($info, true); }catch(Exception $e){ echo $e->getMessage(); }
I get a result like this :
Array
(
[count] => 1
[0] => Array
(
[memberof] => Array
(
[count] => 1
[0] => CN=Administrators,CN=Builtin,DC=my,DC=server,DC=host,DC=com
)
[0] => memberof
[name] => Array
(
[count] => 1
[0] => Userfirstname Userlastname
)
[1] => name
[mail] => Array
(
[count] => 1
[0] => user@host.com
)
[2] => mail
[count] => 3
[dn] => CN=Userfirstname Userlastname,CN=Users,DC=my,DC=server,DC=host,DC=com
)
)

3 Comments
Jump to comment form | comments rss [?] | trackback uri [?]