In this post, i’m gonna explain how to connect to a LDAP server via using PHP.

First i wanna talk about some definitions;

LDAP means Lightweight Directory Access Protocol.

As you can understand from it’s name, it is a database which uses directory-tree based structure.

It’s used by OpenLDAP, Sun Directory Server, Microsoft Active Directory and such directory services.

LDIF means LDAP Data Interchange Format.

You can easily execute LDAP queries using ldif files. For example;

dn: cn=John Doe,dc=example,dc=com
cn: John Doe
givenName: John
sn: Doe
telephoneNumber: +1 888 555 6789
telephoneNumber: +1 888 555 1232
mail: john@example.com
Manager: cn=Jane Doe,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top

You can see some other terms(actually attributes) in the LDAP query above. Such as dn: Distinguished Name, cn: Common Name, sn: Surname.

I’ll give more information about LDAP later in another post.

PHP LDAP Functions

PHP has it’s own LDAP functions by it’s own. But i’ve decided to write a class for easier access to these functions.

First, you have to include our class below.

<?php 

class LDAP{

    public  $ldapserver = "99.245.56.89";
    public  $ldapport = "389";
    public  $basedn = "cn=admin,dc=web-sistem,dc=com";
    public  $basepass = "yourldap_password"; 

	function connect($server,$port){

		echo "Connecting to LDAP Server..."; 
		$connection = ldap_connect($server,$port);  // must be a valid LDAP server!	
		ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);

		// PHP Reference says there is no control of connection status in OpenLDAP 2.x.x
		// So we'll use binding function to check connection status.

		return $connection;

	}

	function bind($connection,$basedn,$basepass){

		echo "<br><br>Binding...<br>";  
		$ldaprdn  = $basedn;    // ldap rdn or dn 
		$ldappass = $basepass;  // associated password
		$bind = ldap_bind($connection, $ldaprdn, $ldappass);

		if ($bind) { 
			echo "LDAP bind successful...";

		} else { 
			echo "LDAP bind failed..."; 
		}
	}

	function search($connection, $searchdn, $filter, $attributes = array()){

		$sr = ldap_search($connection, $searchdn, $filter, $attributes);

		if ($sr) {
			echo 'Search Succeeded. Getting Entries...<br>';

	        echo "Number of entires returned:  " . ldap_count_entries($connection, $sr) . "<br />";

	        $info = ldap_get_entries($connection, $sr);

	        echo "Data for " . $info["count"] . " items returned:<p>\n";

			print_r($info);
			echo '<hr><br>';

		} else {
			echo 'Search Failed.<br>';
		}
	}

	function addRecord($connection, $adddn, $record){

	    $addProcess = ldap_add($connection, $adddn, $record);

	    if($addProcess){
	        echo "Entry added<br>";
			echo '<hr><br>';
	    } else {
	    	echo "Please check your data<br>";
			echo '<hr><br>';
	    }
	}

	function modifyRecord($connection, $modifydn, $record){
		$modifyProcess = ldap_modify($connection, $modifydn, $record);
	    if($modifyProcess){
	        echo "Entry modified<br>";
			echo '<hr><br>';
	    } else {
	    	echo "Please check your data<br>";
			echo '<hr><br>';
	    }
	}

	function deleteRecord($connection, $dn, $recursive = false){
	    echo "Deleting Record...<br>";

	    if($recursive == false){
	    	echo 'Entry: ' . $dn . ' deleted.';
	        return(ldap_delete($connection, $dn));
	    } else {

	        // Search for child entries	        
	        $sr = ldap_list($connection, $dn, "ObjectClass=*", array(""));
	        $info = ldap_get_entries($connection, $sr);

	        for($i=0;$i<$info['count'];$i++){
	            // Recursive delete child entries - using myldap_delete to recursive deletion
	            $result = myldap_delete($connection, $info[$i]['dn'], $recursive);
	            if(!$result){
	                // return status code if deletion fails.
	                return($result);
	            }
	        }
			// Delete top dn
			echo 'Entry: ' . $dn . ' deleted.';
	        return(ldap_delete($connection, $dn));
	    }
	}

	function close($connection){
		echo '<hr><br>';
	    echo "Closing connection";
	    ldap_close($connection);
	}

}

?>

And then you may want to initialize and use our class. Usage is so simple.

<?php

	require_once('class.ldap.php');

	$ldap = new LDAP();

	// Connect to LDAP Server  - connect(ldap_server, port)
	$connection = $ldap->connect($ldap->ldapserver,$ldap->ldapport);

	// Bind with LDAP instance
	$ldap->bind($connection,'cn=admin,dc=web-sistem,dc=com','yourldap_password');

	echo '<hr><br>';

	// Search LDAP directory

	// Search with a wildcard
	$ldap->search($connection,'o=hosting,dc=web-sistem,dc=com','vd=*');

	// Search with no attributes specified	
	$ldap->search($connection,'o=hosting,dc=web-sistem,dc=com','vd=plugged.in');

	// Search with attributes (attributes must be an array)

	$ldap->search($connection,'o=hosting,dc=web-sistem,dc=com','vd=web-sistem.com', array('custID'));

	// Prepare data to insert

	// Please change the record entry as required by your company directory structure

	$insert_data['objectclass'][0] = "top";
	$insert_data['objectclass'][1] = "VirtualDomain";

	$insert_data["accountActive"] = "TRUE";
	$insert_data["delete"] = "FALSE";
	$insert_data["lastChange"] = "103";
	$insert_data["vd"] = "plugged.in";
	$insert_data["adminID"] = "3";
	$insert_data["custID"] = "2";
	$insert_data["editAV"] = "FALSE";
	$insert_data["maxAlias"] = "20";
	$insert_data["maxMail"] = "22";
	$insert_data["maxQuota"] = "300";
	$insert_data["postfixTransport"] = "maildrop:";

	// LDAP Insert DN		
	$addDN = "vd=plugged.in,o=hosting,dc=web-sistem,dc=com";
	$ldap->addRecord($connection,$addDN,$insert_data);

	// Prepare data to modify

	// Please change the record entry as required by your company directory structure

	$modify_data["adminID"] = "3213";
	$modify_data["custID"] = "2441";

	// LDAP Modify DN		
	$modifyDN = "vd=plugged.in,o=hosting,dc=web-sistem,dc=com";
	$ldap->modifyRecord($connection,$modifyDN,$modify_data);

	// Delete LDAP record	(third parameter is "Recursive")
	$deleteDN = "vd=plugged.in,o=hosting,dc=web-sistem,dc=com";
	$ldap->deleteRecord($connection,$deleteDN,true);

	//Close LDAP Connection
	$ldap->close($connection);
?>

That’s all for now.

If you have questions or advices about this class please leave a message in comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *