LDAP修改活动目录多OU搜索

时间:2011-12-15 10:54:08

标签: php active-directory ldap

我有这个脚本,当我只使用一个OU时工作正常。但是,只要我将$ ldapbase放入一个数组并定义多个OU,它就会停止工作@ldap_get_entries和ldap_modify。我知道为什么但不确定如何相应地修改代码。

是否有办法分析整个林根,而不必定义OU,或只是获取samaccountname = $ username的OU。

 <?php
    $username=$_GET['username']; 

    if(isset($_POST['printpin'])) {

    $printpin=$_POST['printpin'];   
    $domadlogin = 'admin@dom.co.uk';
    $domadpw = 'pass';

    $ldapServer = "dc.dom.co.uk";

    $ldapBase[] = "OU=Users1,DC=dom,DC=co,DC=uk";
    $ldapBase[] = "OU=Users2,DC=dom,DC=co,DC=uk";
    $ldapBase[] = "OU=Users3,DC=dom,DC=co,DC=uk";

    $ds = ldap_connect($ldapServer);
    if (!$ds) {die('Cannot Connect to LDAP server');}

    $ldapBind = ldap_bind($ds,$domadlogin,$domadpw);
    if (!$ldapBind) {die('Cannot Bind to LDAP server');}

    ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

    foreach($ldapBase as $dn){ 
    $sr = ldap_search($ds, $dn, "(samaccountname=$username)");
    }

    $ent= ldap_get_entries($ds,$sr);
    $dn=$ent[0]["dn"];
    $newinfo['primaryTelexNumber']= $printpin;

    $save = ldap_modify($ds, $dn, $newinfo);

    if (!$save) {die('Cannot save to LDAP server');}
    ?>

    <p>Your new PIN number has now been set.</p>
    <p>Username:&nbsp;<?php echo $username; ?><br />PIN:<?php echo $printpin; ?></p>

    <?php
    }
    else {
    ?>

    <p>Username:&nbsp;<?php echo $username; ?></p>
    <form action="pin.php?username=<?php echo $username; ?>" method="POST">
    PIN: <input type="text" name="printpin" title="printpin"/>
    <input type="hidden" name="username" value="<?php echo $username; ?>"/>
    <input type="submit" value="Save">
    </form> 


    <?php
    }
    ?>

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:0)

您应该将更多代码移到 foreach 循环并添加一些类似的检查:

foreach ($ldapBase as $dn){ 
    $sr = ldap_search($ds, $dn, "(samaccountname=$username)");
    $ent = ldap_get_entries($ds, $sr);

    if ($ent === false || $ent['count'] === 0)
        continue;

    $dn = $ent[0]['dn'];
    $newinfo['primaryTelexNumber'] = $printpin;

    $save = ldap_modify($ds, $dn, $newinfo);

    if (!$save)
        die('Cannot save to LDAP server');

    break;
}

如果要搜索和修改所有OU,请在循环中删除最后一个中断