Backend Development 4 min read

Using PHP LDAP Functions for Connecting, Binding, and User Authentication

This tutorial explains how to use PHP's LDAP functions to connect to an LDAP server, bind a user, and authenticate credentials, providing complete example code for each step to enable secure authentication in web applications.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP LDAP Functions for Connecting, Binding, and User Authentication

LDAP (Lightweight Directory Access Protocol) is a protocol for accessing distributed directory information and is commonly used for user authentication and authorization in web applications.

1. Connect to LDAP server

Use the ldap_connect function to establish a connection to the LDAP server. Example code:

<?php
$ldapserver = 'ldap.example.com';
$ldapport = 389; // 默认端口号

$ldapconn = ldap_connect($ldapserver, $ldapport)
    or die("无法连接到LDAP服务器:$ldapserver");
?>

2. Bind to LDAP server

After connecting, use ldap_bind to bind a user (e.g., admin) to the server, optionally setting the protocol version with ldap_set_option . Example code:

<?php
$ldaprdn = 'cn=admin,dc=example,dc=com';
$ldappass = 'adminpassword';

ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); // 设置LDAP协议版本为3

$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
if ($ldapbind) {
    echo "LDAP绑定成功!";
} else {
    echo "LDAP绑定失败!";
}
?>

3. User authentication

Search for the user’s DN with ldap_search and retrieve entries with ldap_get_entries . If a single entry is found, bind with the supplied password using ldap_bind to verify credentials. Example code:

<?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 "用户认证成功!";
    } else {
        echo "用户名或密码错误!";
    }
} else {
    echo "用户不存在!";
}
?>

The article demonstrates the complete flow of connecting to an LDAP server, binding, and authenticating users using PHP’s LDAP functions, enabling secure user management in web applications.

backendauthenticationPHPTutorialldapdirectory
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.