Using PHP LDAP Functions to Connect, Bind, and Authenticate Users
This tutorial explains how to use PHP's LDAP functions—ldap_connect, ldap_bind, ldap_search, and ldap_get_entries—to establish a connection to an LDAP server, bind an administrator account, and perform user authentication with example code for each step.
LDAP (Lightweight Directory Access Protocol) is a protocol for accessing and maintaining distributed directory information, commonly used for user authentication and authorization in web applications. PHP provides a set of functions to work with LDAP, and this guide shows how to use them.
1. Connect to the LDAP Server
Use the ldap_connect function to open a connection to the LDAP server. The following example connects to ldap.example.com on the default port 389 and aborts with an error message if the connection fails.
<?php
$ldapserver = 'ldap.example.com';
$ldapport = 389; // default port
$ldapconn = ldap_connect($ldapserver, $ldapport)
or die("Unable to connect to LDAP server: $ldapserver");
?>2. Bind to the LDAP Server
After establishing a connection, bind an account to the server using ldap_bind . The example below binds the administrator user cn=admin,dc=example,dc=com with a password, after setting the LDAP protocol version to 3.
<?php
$ldaprdn = 'cn=admin,dc=example,dc=com';
$ldappass = 'adminpassword';
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); // set protocol version to 3
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
if ($ldapbind) {
echo "LDAP bind successful!";
} else {
echo "LDAP bind failed!";
}
?>3. User Authentication
To authenticate a user, first search for the user's distinguished name (DN) with ldap_search and retrieve the entry using ldap_get_entries . If exactly one entry is found, bind with the supplied password to verify the credentials.
<?php
$username = 'user1';
$password = 'password1';
$searchFilter = "(uid=$username)";
$searchResult = ldap_search($ldapconn, 'ou=users,dc=example,dc=com', $searchFilter);
$entry = ldap_get_entries($ldapconn, $searchResult);
if ($entry['count'] == 1) {
$ldaprdn = $entry[0]['dn'];
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $password);
if ($ldapbind) {
echo "User authentication successful!";
} else {
echo "Invalid username or password!";
}
} else {
echo "User does not exist!";
}
?>These steps demonstrate the basic workflow for connecting to an LDAP server, binding an administrator account, and authenticating users using PHP's LDAP functions, enabling web applications to manage and authorize access securely.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.