User password changes with LDAP and PHP

Once you've started using LDAP for authentication, you'll probably want to let your users change their passwords. Since they might not want to/be able to do a shell login, and change their password with ldappasswd(1), something else, and more user friendly would be nice.

I chose using PHP, which I have compiled with LDAP support. Using Apache with SSL support, the passwords didn't have to travel over the wire in plaintext.

Now, users should only be able to change their own passwords, and nothing but the password. This was acheived with this stanza in slapd.conf

access to attr=userPassword
        by self write
        by anonymous auth
        by * none

The next step then, is authenticating the user, by doing an ldap bind with his credentials:

  if(isset($username) and isset($newpass) and isset($oldpass)) {
     $ldapconn = ldap_connect("", 389);
     $ldapbind = @ldap_bind($ldapconn,"uid=".$username.",dc=example,dc=com",$oldpass);
     if($ldapbind) {

If the bind with the old password succeeds, the user has entered the right username/password combination. To change the passwd we then do:

  print "<p>Change password ";
  if(ldap_mod_replace ($ldapconn, "uid=".$username.",dc=example,dc=com", 
array('userpassword' => "{MD5}".base64_encode(pack("H*",md5($newpass))) { 
    print "succeded"; } else { print "failed"; }
  print ".</p>\n";

Pretty simple, eh?

Karyl F. Stein has written a much more elaborate php ldap password changer. It used to be located at, but the page seems to have been shut down.

Valid XHTML 1.1! Valid CSS!
Last updated: 2006-03-28 09:55