Search code examples
phpactive-directoryldapwindows-server-2008-r2

Change LDAP user password using PHP in windows server 2008


I want to let my active directory users to change their passwords from a linked form with PHP code. when I used ldap_modify function, it changes the mail but it never change the password, however it replied with success message. I use this to encrypt the password:

  $encoded_newPassword = "{SHA}" . base64_encode( pack( "H*", sha1( $newPassword ) ) );


Solution

  • To do a password change, you need to follow the procedure and format described in the documentation for the unicodePwd attribute. You have to do two operations in the same request:

    • A remove operation that includes the old password, and
    • An add operation that includes the new password

    And both passwords have to be in a specific format.

    To do this in PHP, you use ldap_modify_batch. In the documentation for ldap_modify_batch there is an example of how to do a password change:

    function adifyPw($pw)
    {
        return iconv("UTF-8", "UTF-16LE", '"' . $pw . '"');
    }
    
    $dn = "cn=Jack Smith-Jones,ou=Wizards,dc=ad,dc=example,dc=com";
    $modifs = [
        [
            "attrib"  => "unicodePwd",
            "modtype" => LDAP_MODIFY_BATCH_REMOVE,
            "values"  => [adifyPw("Tr0ub4dor&3")],
        ],
        [
            "attrib"  => "unicodePwd",
            "modtype" => LDAP_MODIFY_BATCH_ADD,
            "values"  => [adifyPw("correct horse battery staple")],
        ],
    ];
    ldap_modify_batch($connection, $dn, $modifs);