Category Archives: Active Directory

Authenticating users against Active Directory with PHP

A co-worker of mine asked how this can be done, since I’ve already had some experience querying AD with Java and PHP. It’s been some time ago so I had to think about a little but then I realized it’s easy. Just use LDAP bind!

Consider the following PHP code snippet:

$ldaphost = ‘ldap://dc.mycompany.local’;
$ldapport = 389;

$user = ‘DOMAIN\user’;
$password = ‘password’;

$ldapconn = @ldap_connect( $ldaphost, $ldapport );
if( $ldapconn )
{

ldap_set_option( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
ldap_set_option( $ldapconn, LDAP_OPT_REFERRALS, 0 );

$ok = @ldap_bind( $ldapconn, $user, $password );
if( $ok )
{
ldap_unbind( $ldapconn );
}
else
{
echo ‘Failed to bind to LDAP server:’ . “\n”;
echo ldap_error( $ldapconn ) . “\n”;
}
}
else
{
echo ‘Failed to connect to LDAP server’ . “\n”;
}

It is important to prefix the user’s name with the domain otherwise it won’t accept it and obviously in real life you’d want to use LDAPS and not send the password over the wire in clear text, but the basic idea is the same.

Advertisements