Friday, April 3, 2009

Use LDAP EXOP to change userpassword in PHP

It seems to me I couldn't do LDAP EXOP directly in PHP 5. However, the CPAN module Net::LDAP::Extension::SetPassword can do it and I can use Perl Code from PHP. I installed the Net::LDAP in CPAN and php-perl by urpmi. Then the following PHP code is what I have to change LDAP UserPassword by EXOP (connection is by ldapi):


$perl = new Perl();

try {
$perl->eval('
use Net::LDAP;
use Net::LDAP::Extension::SetPassword;
$errtxt="";

sub changepass {
my $server=shift @_;
my $dn=shift @_;
my $oldpass=shift @_;
my $newpass=shift @_;

$ENV{LDAPI_SOCK}="/var/run/ldap/ldapi";
$ldap = Net::LDAP->new( $server, onerror => "warn" );
$ldap->bind($dn , password => $oldpass);
$mesg = $ldap->set_password( oldpasswd => $oldpass, newpasswd => $newpass);
$errtxt=$mesg->error();
return $mesg->code();
}
');

$server='ldapi://';
$dn='uid=user,ou=People,dc=example,dc=com';
$oldpass='oldsecret';
$newpass='newsecret';

$errno=$perl->changepass($server,$dn,$oldpass,$newpass);
$error=$perl->errtxt;

}

catch (PerlException $exception) {
echo "Perl error: " . $exception->getMessage() . " ";
}

if ($errno) {
echo "Error $errno: $error";
}

1 comment:

Unknown said...

That reminds me of my later Pascal days in Turbo Pascal, where most of my programs began with

begin
asm

end;

Nice article though, and it seems that I can finally get rid of PHP from my LDAP server :)