PHP Active Directory Password Reset

LDAP is the Lightweight Directory Access Protocol, a protocol used to access and manage Directory Servers such as Active directory. The Directory is a special kind of database that holds information in a tree structure. This php function which resets an active directory account password, accept three variables, one is the domain controller IP, samaccount name and a password. To get this function working, You will need to get and compile LDAP client library from either OpenLDAP and compile PHP with LDAP support. OpenLDAP Software is an open source implementation of the Lightweight Directory Access Protocol.

Please refer this post forĀ  ldap library installation.

function resetpassword($serveraddress,$user,$password)
{

$ldaprdn  = 'CN=domainadmin,CN=Users,DC=domain,DC=local';
$ldappass = "yourpassword";  // associated password
$ldapconn = ldap_connect($serveraddress ) or die("Could not connect to LDAP server.");
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);

if ($ldapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo $serveraddress." AD bind successful...";

        $samaccountname = $user;

        $filter="(samaccountname=$samaccountname)";
        $dn="OU=Users,DC=domain,DC=local";

        $res = ldap_search($ldapconn, $dn, $filter);
        $first = ldap_first_entry($ldapconn, $res);
        $data = ldap_get_dn($ldapconn, $first);
        $dn = $data;
        $newPassword = "\"" . $password . "\"";
        $newPass = mb_convert_encoding($newPassword, "UTF-16LE");
        $newEntry = array('unicodePwd' => $newPass);

        $newEntry["lockouttime"][0]=0;
        
        print_r($newEntry);

        if(ldap_mod_replace($ldapconn, $dn, $newEntry))
        { print "<p>succeeded</p>";  }
        else {        print "<p>failed</p>";    }

        $resulttext =  ldap_error($ldapconn);
        echo '<p style="color: green;font-size: xx-large;">  '.'Result:'.$resulttext. ' </p>';

        }
             else {
                             echo "LDAP bind failed...";
                            print_r(ldap_error($ldapconn));
                    }
                    print "<p>";
              }
   }

The function can be invoked as

$serveradd = "ldaps://domaincontrollerip:636"; // domain controller 
$user = "domainuser"; // domain user account
$password = "newpasswordtoset";

resetpassword($serveradd,$user,$password);

 

Please follow and like us: