How can I connect to Active Directory using LDAPS on PHP?

I was wondering how to connect to my Active Directory Domain Controller using LDAPS in PHP on another windows server. I have exported the root certificate and the server certificate and put the root in my trusted root store and the server authentication in my personal certificates in my windows certificate store. When I try to connect using port 389 it's fine, but when I try to connect using port 636 I get an error.

 // LDAP variables <br>
 $ldap_host = "myhost";   // your ldap servers<br>
 $ldap_port = 636;          // your ldap server's port number<br>
 $base_dn = "OU=Users,OU=domain,DC=example,DC=local";<br>

// Connecting to LDAP<br>
$connect = ldap_connect( $ldap_host, $ldap_port)<br>
or exit(">>Could not connect to LDAP server<<");<br>
echo "Connected to $ldap_host";<br>

ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);<br>
$ldap_user  = "CN=UserName,OU=No Policy,DC=example,DC=local";<br>
$ldap_pass = "Password";<br>
// verify binding<br>
$bind = ldap_bind($connect, $ldap_user, $ldap_pass)<br>
or exit(">>Could not bind to $ldap_host<<" . ldap_error($connnect) );<br>

The output I get is "Connected to myhost Could not bind to myhost.
When using port 389 I get "connected to myhost"

1 answer

  • answered 2019-02-06 05:10 heiglandreas

    As stated in the docs you need to use an LDAP-URI to connect via LDAPS.

    In your case that would look like this:

    ldap_connect('ldaps://'. $ldap_host. ':'. $ldap_port);