ldaps with php

Just a simple example script showing how to connect to a directory server over LDAPS using php.

Here’s the code:

<?php

$dirHost = "ldaps://localhost:1636";
$usrbase = "dc=example,dc=com";
$query = "(uid=philip)";
$ds = ldap_connect($dirHost);
ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
$r = ldap_bind($ds);
$sr = ldap_search($ds, $usrbase, $query);
$info = ldap_get_entries($ds, $sr);
for($i=0; $i<$info["count"]; $i++) {
    $dn = $info[$i]["dn"];
    $street = $info[$i]["street"];
    $l = $info[$i]["l"];
    $st = $info[$i]["st"];
    $c = $info[$i]["c"];
    $postalcode = $info[$i]["postalcode"];
    echo "dn: $dn\n";
}
ldap_close($ds);
?>

Note that before doing this I edited my local /etc/openldap/ldap.conf, commenting out everything that was already there and adding:

TLS_REQCERT never
TLS_CACERTDIR /etc/pki/tls/certs

This allows me to connect to servers with self-signed certs, as php’s LDAP module suffers from 2 shortcomings: (1) dependence on openldap’s local config; (2) abysmal handling of SSL certificates. Server certs are stored in the common /etc/pki/tls/certs directory.

Perl’s Net::LDAP module is significantly more sophisticated and flexible than the corresponding php module, so much so that I’ve considered using php only for the presentation layer while relying on perl for the backend functions when writing new web applications.

This entry was posted in Directory on by .

About phil

My name is Phil Lembo. In my day job I’m an enterprise IT architect for a leading distribution and services company. The rest of my time I try to maintain a semi-normal family life in the suburbs of Raleigh, NC. E-mail me at philipATlembobrothersDOTcom. The opinions expressed here are entirely my own and not those of my employers, past, present or future (except where I quote others, who will need to accept responsibility for their own rants).