1.7 Accessing LDAP Directories from PHP

LDAP (Lightweight Directory Access Protocol) is used to access directory servers. Directory is a special kind of database that holds information in a tree structure. PHP for NetWare can access an LDAP directory through the LDAP extension.

Add the following line under NetWare Extensions section in the php.ini file, before accessing LDAP directories from PHP:

extension=php_ldap.nlm

The PHP LDAP extension will be loaded automatically when Apache is loaded if Apache is configured for PHP.

1.7.1 Executing a LDAP Directory Sample

The following sample (ldapquery.php) connects and binds to Novell’s LDAP server and then searches and displays all the Surname entries starting with the letter, S.

The sample is copied along with the PHP binaries in the sys:\php\webdemo directory. To use it, you will need to copy it to sys:\apache\htdocs directory or a subdirectory under htdocs directory.

Then, enter the URL, of the form http://Server_name:port_number/Destinationfolder/scriptname

For example, the URL for executing the script ldapquery.php located under sys:/apache/htdocs/phpscripts will be

http://server_name:port_number/phpscripts/ldapquery.php.

   <html>
   
   <head>
   <title>LDAP Query</title>
   
   </head>
   
   <body>
   <font face="Courier New" size="-1">
   
   <h3>LDAP Query Test</h3>
   
   <?php
    $ds = ldap_connect("http://nldap.com");  // must be a valid LDAP
   server.
    echo "connect result is ".$ds."<p>";
   
    if ($ds) { 
        $r=ldap_bind($ds);     // this is an "anonymous" bind,
   typically
                               // read-only access
        echo "Bind result is ".$r."<p>";
   
        // Search surname entry
        $sr=ldap_search($ds,"c=US", "sn=S*");  
        echo "Search result is ".$sr."<p>";
        echo "Number of entires returned is
   ".ldap_count_entries($ds,$sr)."<p>";
   
        $info = ldap_get_entries($ds, $sr);
        echo "Data for ".$info["count"]." items returned:<p>";
   
        for ($i=0; $i<$info["count"]; $i++) {
            echo "dn is: ". $info[$i]["dn"] ."<br>";
            echo "first cn entry is: ". $info[$i]["cn"][0] ."<br>";
            echo "first email entry is: ". $info[$i]["mail"][0]
   ."<p>";
        }
   
        ldap_close($ds);
   
    } else {
        echo "<h4>Unable to connect to LDAP server</h4>";
    }
   ?>
   
   </font>
   
   </body>
   
   </html>