LDAP authentication with Active Directory using PHP

Just a quickie for anyone looking to authorise users on a PHP driven website by directly connecting to a Windows Server’s Active Directory using LDAP. The little script below is a very (very) basic method to connect to an Active Directory (AD) and pull out all the details required.

If you are used to using MySQL to store user info and have used login systems which query the database and pull out the user’s details then you may find connecting to LDAP a little different. With a PHP LDAP connection you do not connect to the database and then see if a user exists, you actually connect to the AD using the user’s passed credentials and if it successfully connects then you know you are authenticated – you can then pull the users info out if required. and perform extra checks. By default the AD is readable by all authenticated users so you should not have permission problems unless the IT administrator has locked down the AD a little too much – which lets face it is highly possible!!

So – on to it. There ae two versions below – the first is for basic authentication and the second is for a connection over ldaps with TLS (or SSL) enabled. Both the below connect to to the AD server using LDAP/s, binds to AD using the user’s details to authenticate but the first returns all the users’ info using the query (cn=*) – the asterisk being a wildcard for all users – and the second one just pulls to required user’s info using the (cn=$ldapuser) query. Hopefully it all makes sense but if not then comment below and I’l try to do a bterr job of explaining it all.

One final thing I need to mention is that you need to make sure you query the correct AD tree – the first version below is set for a default Windows 2003 Small Business Server setup – SBSUsers/Users/MyBusiness/Domain/tld – you can change this by editing the $ldaptree variable to suit.

So – version one – return all users (default connection type):

http://mj7.co.uk/ajc3

And version 2:

http://mj7.co.uk/ajdw

So hopefully somene finds them useful – any questions just comment below.

As always – tweet if you like, link if you use.

About the Author

MJ7: aka Mark Jackson @ MJDIGITAL. Digital Consultant - primarily digital marketing, web app design and development, multimedia and SEO techniques. But will happily consult on most IT matters.