Nathan Friend Nathan Friend - 7 months ago 49
PHP Question

Set password when creating a new Active Directory user account in PHP

This PHP script creates enabled user accounts in Active Directory without a password. How do I set the password?

$examplePassword = "34mlrfm$sxkf";
$WinTimestamp = "131196672000000000" //30-09-16 00:00:00

//Create unicode password
function encodePassword($password) {
for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000";}
return $encoded;

//Build Active Directory record
$ldaprecord["accountExpires"] = $winTimestamp;
$ldaprecord["UserAccountControl"] = "544"; //544 - Account enabled, require password change
$ldaprecord['userPassword'] = encodePassword($examplePassword);
$ldaprecoed['otherAttributes'] = "Truncated from question";

$ds = ldap_connect($AD_server); // Connect to Active Directory
if ($ds) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$r = ldap_bind($ds, $AD_Auth_User, $AD_Auth_PWD); //Bind
$r = ldap_add($ds,$dn,$ldaprecord); //Create account
ldap_close($ds); //Close connection

I've tried different password encoding methoods.

I've also tried inserting the password into $ldaprecord["unicodepwd"]. Which results in "Server is unwilling to perform" error.


I've got it working. You can only set passwords over an SSL connection, thanks @stuartbrand

Either encrypt traffic on 389 using ldap_start_tls() or connect on 636 using $ds = ldap_connect('ldaps://'.$AD_server);

Password should be inserted into the $ldaprecord["unicodepwd"] attribute.