首先,網頁伺服器需支援php-ldap模組如未安裝,請使用yum install php-ldap(Linux)或修改php.ini 檔案中的 php extension部份
找過很多網站,都無法新增後來找了很多phpldap中的屬性關聯才知道例如:inetOrgPerson 的 objectClass cn 跟 sn 是必須的而 mail、uid 則是選擇性有些要使用request屬性,有些是選用的詳細請使用 phpldapadmin 或 AdExplorer 的 Scheme 檢閱
以下為範例程式碼,在我的系統中執行是可以用的inc.php的設定檔
class AD{ //指定初始值 var $server = "localhost"; var $adminuser = "uid=root, cn=users, dc=example, dc=org, dc=tw"; var $adminpassword = "***"; var $ou = "cn=users, dc=example, dc=org, dc=tw"; var $_ldapconn; //連結AD(LDAP) function ldapconn(){ //連線到AD(LDAP)Server $ldapconn = ldap_connect($this->server) or die("無法連線到伺服器!"); //使用LDAP Version 3 ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0); $this->_ldapconn = $ldapconn; return true; } //新增AD(LDAP)資料 function ldapadd($uid, $array) { ldap_bind($this->_ldapconn, $this->adminuser, $this->adminpassword); return ldap_add($this->_ldapconn, "uid=".$uid.",cn=users,dc=sunnyswa,dc=org,dc=tw", $array); } //修改AD(LDAP)資料 function ldapmodify($uid, $array) { ldap_bind($this->_ldapconn, $this->adminuser, $this->adminpassword); return ldap_modify($this->_ldapconn, "uid=".$uid.",cn=users,dc=sunnyswa,dc=org,dc=tw", $array); } }?>
主程式 新增LDAP(ldapadd.php)
//匯入設定檔include "inc.php"; $ad = new AD(); $ad->ldapconn(); $array['objectClass'][0] = "top"; //AD Request /*$array['objectClass'][1] = "organizationalPerson"; $array['objectClass'][2] = "person"; $array['objectClass'][3] = "user"; *///LDAP Request$array['objectClass'][1] = "posixAccount"; $array['objectClass'][2] = "shadowAccount"; $array['objectClass'][3] = "inetOrgPerson"; $array['objectClass'][4] = "organizationalPerson"; $array['objectClass'][5] = "person"; $array['objectClass'][6] = "apple-user"; $array['cn'] = "test"; $array['uid'] = "test"; $array['uidNumber'] = "1000098"; $array['gidNumber'] = "1000001"; $array['loginShell'] = "/bin/sh"; $array['homeDirectory'] = "/home/".$array['uid']; $array['sn'] = "test"; $array['authAuthority'] = ";basic;"; $array['gecos'] = "test"; $array['displayName'] = "test"; $array['userPassword'] = "{CRYPT}".crypt($password, "$1$k0Q4EA49$"); //User Chioce$array['telephoneNumber'] = "03-4618007"; $array['mobile'] = "0912-345678"; $array['employeeNumber'] = "101017"; $array['title'] = "test"; $array['mail'] = $array['uid']."@sunnyswa.org.tw"; //AD Request//$array['name'] = "test"; //$array['userPrincipalName'] = "[email protected]"; //$array['userAccountControl'] = "544"; $insert = $ad->ldapadd("uid=".$array['uid'].", cn=users, dc=example, dc=org, dc=tw", $array); if($insert){ echo "ok"; }else{ echo "fail"; }?>
修改方面的程式與新增雷同另外,因為我是用synology的nas所以它的密碼編碼是CRYPT,所以這樣寫是符合它的規則AD必填的與LDAP 必填的有特別註解,大家就自行取用囉CN如果要跟我一樣使用變數的話就要這樣寫才會過$array = array(“cn” => $name);只有這個屬性需要這樣寫,其餘則不用
還有如果要一個屬性套用同一個資料就用$array[‘displayName’] = $array[‘cn’];
刪除LDAP資料目前還沒有研究出來,過段時間再補