17.1 Adding an Entry to an LDAP Server


You want to add an entry to an LDAP server. In the following example, we will add Doc Brown.

Technique

Use the ldap_add() function after binding with write access to the LDAP server:

 <?php // connect and bind $lh = ldap_connect("localhost") or die("Cannot connect to the LDAP server"); ldap_bind($lh, "cn=root, o=Sterling's Company, c=US", "password")        or die("Cannot Bind"); // build the data $data["cn"] = "Doc Brown"; $data["objectclass"] = "Person"; // add the data and close the connection ldap_add($lh, "cn=Doc Brown, o=Sterling's Company, c=US", $data); ldap_close($lh); ?> 

Comments

In this example, we add an entry for Doc Brown, who is an employee of the company named Sterling's Company, which is located in the United States. We achieve this by first connecting to the LDAP server on localhost . Then we bind the server and specify a password, which is necessary if we want to add, delete, and modify entries. We then build the data for Doc Brown into an associative array and use ldap_add() to add him to the directory.

Make special note of the ldap_bind() function in which you need to specify a password when you want to have write access to the LDAP server. Also note that ldap_close() is really an alias for ldap_unbind() and the two different functions can be used interchangeably. Therefore, we could have written

 ldap_unbind($lh); 

and it would have achieved the same effect.

If you want to add attributes to a preexisting entry, simply use the ldap_mod_add() function like so:

 <?php // connect and bind, notice the password is specified // when we bind the connection $lh = ldap_connect("localhost") or die("Cannot connect to LDAP server"); ldap_bind($lh, "cn=root, o=Sterling's Company, c=US", "password")            or die("Cannot Bind to LDAP Server"); // Build the data $data["sn"] = "Brown"; $data["mail"] = "sterling@designmultimedia.com"; // Add the data and close the connection ldap_mod_add($lh, "cn=Doc Brown, o=Sterling's Company, c=US", $data); ldap_close($lh); ?> 

This would add the attributes of sn ( surname ) and mail (email address) to the Doc Brown entry in the LDAP server.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net