LDAP connect using V3 protocol

Posted under » PHP on 25 October 2015

You must have PHP5 LDAP installed before this can work.

Using LDAP bind is the basic LDAP tool.

$ldaprdn  = 'hanafi@astar.edu.sg';     // ldap rdn or dn
$ldappass = 'MrLKYisUgly';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("108.80.70.5")
    or die("Could not connect to LDAP server.");
if ($ldapconn) {
    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }
}

In most cases, you need to define more things.

<¿php
$ldap_host = "ldap.php.net.sg";
$ldap_port = "389";

$base_dn = "dc=php,dc=net,dc=sg";
$filter = "(cn=hanafi)";
$ldap_user  = "cn=hanafi,ou=people,dc=php,dc=net,dc=sg";
$ldap_pass = "taik";
$connect = ldap_connect( $ldap_host, $ldap_port)
         or exit(">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($connect, $ldap_user, $ldap_pass)
      or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
      or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned

"; $ii=0; for ($i=0; $ii<$info[$i]["count"]; $ii++){ $data = $info[$i][$ii]; echo $data.": ".$info[$i][$data][0]."
"; } ldap_close($connect); ?>

Another way. This time without password or anonymous connect.

<¿php

// LDAP variables
$ldap_host = "ldap.php.net.sg";
$ldap_port = "389";

// Connecting to LDAP
$connection = ldap_connect($ldaphost, $ldapport)
          or die("Could not connect to $ldaphost");

$bind = ldap_bind($connection);

$query = ldap_search($connection, 'ou=zgroups,dc=ldap,dc=php,dc=net', 'cn=all');

$query_result = ldap_get_entries($connection, $query);

for ($k=0; $k<$query_result[0]["uniquemember"]["count"]; $k++) 
				{
      echo $query_result[0]["uniquemember"][$k]." -
"; } ldap_close($connection); ?>

If you have just updated your OpenLDAP, you must connect using the V3 protocol or you will get this error. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

ldap error log: conn=1482 op=0 RESULT tag=97 err=2 text=historical protocol version requested, use LDAPv3 instead 

Then add the set_option thingie. This is also shown above on the first LDAP connect example.

// LDAP variables
$ldap_host = "ldap.php.net.sg";
$ldap_port = "389";

// Connecting to LDAP
$connection = ldap_connect($ldaphost, $ldapport)
          or die("Could not connect to $ldaphost");
ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);

 

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data