A web developer’s diary

January 18, 2007

Authenticating an Active Directory user using PHP-LDAP

Filed under: PHP — Celia @ 3:35 pm

Are you having problems in connecting to an AD Directory server using PHP functions? I too had the same problem. There were numerous articles on the web explaining this but still I wasn’t able to figure out how to do this. But then, I decided that I would write an article here if I ever got it right. Thank God!! I finally did.

GETTING STARTED:

I assume that you have the following installed and set up correctly.

1) PHP  with LDAP support.

2) A working active directory server with an organizational structure.

For details on how to get LDAP working for PHP, please refer to http://www.php.net/ldap.

Setting up an active directory server is beyond the scope of this article. You might have to ask your sys admin’s help.
INFORMATION REQUIRED:

You would need to know the following information about your active directory.

1) The server name. If your active directory is installed on the same machine as your PHP, it could very well be ‘localhost’.

2) The port it is listening on. (The default port is 389)

3) The username and password required to bind to the Active directory server.

4) The base DN. (distinguished name).  If you do not know your base dn, please refer to this article.

WORKING IT OUT:

        $ldap_ip=”localhost”;

$ldap_port=389;

$user_name=”celia”;

$pass_word=”celia”;

$ldap_dnname=”dc=CHN, dc=company, dc=com”;
$conn=@ldap_connect($ldap_ip,$ldap_port)

ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);
$bind=@ldap_bind($conn,$user_name,$pass_word);

$bind would tell you if the authentication passed or not. Isn’t this cool? But this is not all. You can also retrieve information about the authenticated user.

$filter=”(|(sn=$user_name*)(cn=$user_name*)(givenname=$user_name*))”;
$sr=ldap_search($conn,$ldap_dnname,$filter);
$info = ldap_get_entries($this->conn, $sr);
The code is self explanatory and hence I haven’t taken the pains to explain it. However, if you do need some clarification here, please feel free to ask me.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: