Thursday 23 May 2013

A Simpler PHP LDAP API

LDAP service and ActiveDirectory service are very commonly used services to hold employee information in large companies and organisations. I was a software engineer worked on a large oilfield service company which implemented the one of the best LDAP service to host over 80K employees records. This is one of the best LDAP services I ever seen.

As you can imaging I have to use the LDAP service to query employee records and authenticate user logins on different projects. Most of the time LAMP is my first choice of the development environment so I have to keep using the PHP ldap API (ldap_connect, ldap_bind etc) to do all sorts of LDAP queries and user authentication.

After several times of keep writing the same code again and again I came up with this simpler PHP LDAP API that you can complete ldap actions in 10 lines of code:

<?php
$portal_username='yufeiliu';
$portal_password='password';
$ldap_user = new LDAPUser();
$ldap_user->setLDAPHost("server", 389);
$ldap_user->setBaseDN('DC=domain,DC=company,DC=com');
$ldap_user->connectLDAPServer();
$ldap_user->setServiceAccount('CN=admin,ou=service,ou=accounts,dc=cs,dc=company,dc=com', 'password');
if($ldap_user->authorizeUser($portal_username, $portal_password)){
  echo "YES\n";
}else{
  echo "NO\n";
}
$ldap_user->disconnectLDAPServer();

?>

This API is not designed commonly to be used at anywhere so you may need to make some changes on the code so you can use it on your projects.

The php code can be downloaded from gist here