How to Connect Securely to LDAP Active Directory using PHP

To connect securely to Active Directory (LDAP) using PHP follow these steps.

  1. Verify that PHP has both the ldap and openssl extensions enabled.
  2. Verify the ldap.conf file settings for Windows/Linux Procedure
    • For Windows, verify that the C:\openldap\sysconf\ldap.conf file exists.
    • For Linux, verify that the /etc/openldap/ldap.conf file exists. If it does not, create it.
    • For both Linux and Windows, the ldap.conf file should contain this line: TLS_REQCERT never
  3. If you want PHP to verify the ldap server’s ssl certificate with the Certificate Authority that issued the certificate, you need to put the root certificate here:
  4. Now copy the rootcert.pem to the certs folder:
    • For Linux, /etc/openldap/cert/rootcert.pem
    • For Windows, C:\openldap\sysconf\certs\rootcert.pem
    • For both Linux and Windows, the ldap.conf file should contain this line: (Linux) TLS_CACERT /etc/openldap/cert/rootcert.pem (Windows) TLS_CACERT c:\OpenLDAP\sysconf\certs\rootcert.pem
// This code uses the TLS command

$ldaphost = "ldap://ldap.example.xyz";
$ldapUsername  = "cn=username,o=novell";
$ldapPassword = "password";
 
 
$ds = ldap_connect($ldaphost);
 
if(!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)){
echo "Could not set LDAPv3\r\n";
}
else if (!ldap_start_tls($ds)) {
echo "Could not start secure TLS connection";
}else {
// now we need to bind to the ldap server
$bth = ldap_bind($ds, $ldapUsername, $ldapPassword) or die("\r\nCould not connect to LDAP server\r\n");
}
// This code goes directly to the 636 SSL port

$ldaphost = "ldaps://ldap.example.any";
$ldapUsername  = "cn=username,o=novell";
$ldapPassword = "password";
 
 
$ds = ldap_connect($ldaphost);
 
if(!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)){
print "Could not set LDAPv3\r\n";
}
else {
// now we need to bind to the ldap server
$bth = ldap_bind($ds, $ldapUsername, $ldapPassword) or die("\r\nCould not connect to LDAP server\r\n");
}

One Comment on “How to Connect Securely to LDAP Active Directory using PHP”

Leave a Reply

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