Configuration and connecting

Configuration and connecting – How to configure Net_LDAP and connect to an LDAP server

Connecting to an LDAP server

To connect to an LDAP server, you should use Net_LDAP's static connect() method. It takes one parameter, an array full of configuration options, and either returns a Net_LDAP object if connecting works, or a Net_LDAP_Error object in case of a failure.

The following table lists all configuration options. If the default value for an option fits your needs, you don't need add it to your configuration array.

Possible configuration options
Name Description Default
host LDAP server name to connect to. You can provide several hosts in an array in which case the hosts are tried from left to right. localhost
port Port on the server 389
version LDAP version 3
starttls TLS is started after connecting false
binddn The distinguished name to bind as (username) (none)
bindpw Password for the binddn (none)
basedn LDAP base name (root directory) (none)
options Array of additional ldap options as key-value pairs array()
filter Default search filter (string or preferably Net_LDAP_Filter object). See LDAP filters (objectClass=*)
scope Default search scope, see Search sub

Connecting to an LDAP server

<?php
// Inclusion of the Net_LDAP package:
require_once 'Net/LDAP.php';

// The configuration array:
$config = array (
    
'binddn'    => 'cn=admin,ou=users,dc=example,dc=org',
    
'bindpw'    => 'password',
    
'basedn'    => 'dc=example,dc=org',
    
'host'      => 'ldap.example.org'
);

// Connecting using the configuration:
$ldap Net_LDAP::connect($config);

// Testing for connection error
if (PEAR::isError($ldap)) {
    die(
'Could not connect to LDAP-server: '.$ldap->getMessage());
}
?>