PHP connect to LDAP

I am working with a project that require connect to a AD to perform the user authorization.
Before configure my application to login using the AD profile, I always using a simple PHP script to connect the AD setting that provided by my customer.

Here is a simple script that let me know that those AD setting is correct or wrong.

<?php
//Connect to LDAP server.
$ds=ldap_connect( "whatevar.com.my", 389 );
 
if ($ds) {
    //Using the provided user and password to login into LDAP server.
    //For the dc, normally will be the domain.
    $r=ldap_bind($ds, "uid=USERID,ou=special users,dc=whatevar,dc=com,dc=my", "PASSWORD");
 
    // You may add in any filter part on here. "uid" is a profile data inside the LDAP. You may filter by other columns depends on your LDAP setup.
    $sr=ldap_search($ds, "dc=whatevar,dc=com,dc=my", "uid=*");
 
    $info = ldap_get_entries($ds, $sr);
 
    for ($i=0; $i<$info["count"]; $i++) {
        //Print out the user information here. For those uid, displayname, userprincipalname and emailaddress are those data inside a user profile. It will be different for your LDAP setup.
        echo "uid is: " . $info[$i]["uid"][0] . "\n";
        echo "displayName entry is: " . $info[$i]["displayname"][0] . "\n";
        echo "userPrincipalName entry is: " . $info[$i]["userprincipalname"][0] . "\n";
        echo "userPrincipalName entry is: " . $info[$i]["emailaddress"][0] . "\n";
    }
    ldap_close($ds);
} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
 
?>

The above PHP script will display out all the user’s profile inside the AD filter by “uid” (it is a unique user data for the each profile. It might be different for each AD setup.)
If you are going to use the above script, please do modify it base on your AD setup.

2 Comments to “PHP connect to LDAP”

  1. Birama 2 June 2011 at 9:46 pm #

    I need to create a web-based system (e.g. via php or any other language) where users are able to access & update some (password and contact) information on the Active Directory from wherever they are.

  2. debarati dutta 2 May 2014 at 5:58 pm #

    thanx


Leave a Reply