Using PHP's OpenLDAP Extension in ServBay
ServBay is a powerful local web development environment that supports multiple tech stacks. For PHP developers who need to interact with an LDAP (Lightweight Directory Access Protocol) server, ServBay comes with the PHP OpenLDAP extension pre-installed, making it easy to enable and use. This article will guide you on how to leverage this extension in your ServBay environment for features like user authentication and directory queries.
What is OpenLDAP and the PHP OpenLDAP Extension?
OpenLDAP is a popular open-source implementation providing directory services based on the LDAP protocol. The LDAP protocol is widely used in enterprise environments for user identity authentication, organizational structure management, address book services, and more.
The PHP OpenLDAP extension (commonly referred to as the ldap
extension) is a PHP module that provides functions to communicate with LDAP servers. With this extension, PHP applications can connect to LDAP servers to perform bind (authentication), search, add, modify, and delete operations on directory entries.
In ServBay, what matters is the OpenLDAP client extension built into PHP, which allows your PHP code to connect to and operate on external LDAP servers. Note that ServBay itself does not include an OpenLDAP server.
Main Features of the PHP OpenLDAP Extension
With PHP's OpenLDAP extension, you can:
- Connect to an LDAP server: Establish a link to a specified LDAP server.
- Perform bind operations: Authenticate either anonymously or with a DN (Distinguished Name) and password.
- Search the directory: Query entries in the directory using filters, base DNs, and scope.
- Read entry information: Retrieve the properties and values of each result entry.
- Perform modification operations: Add new entries, delete entries, or modify entry attributes.
- Handle LDAP errors: Get error details when operations fail.
PHP OpenLDAP Extension Version Compatibility in ServBay
ServBay supports installing and running multiple PHP versions. The PHP OpenLDAP extension is typically included in the official PHP distribution and is enabled by default in the ServBay PHP package. This means that when using ServBay’s provided PHP versions, the OpenLDAP extension is most likely available for you by default.
How to Verify if PHP OpenLDAP Extension is Enabled
Although ServBay is designed as a plug-and-play environment with most common extensions enabled by default, it’s always best practice to verify this. The simplest way is using the phpinfo()
function.
In your ServBay website root directory (default:
/Applications/ServBay/www
), create a new PHP file such asinfo.php
.Add the following content to
info.php
:php<?php phpinfo(); ?>
1
2
3In your browser, visit the address in ServBay associated with this file (for example,
http://servbay.demo/info.php
).On the displayed
phpinfo()
page, look for a section namedldap
.If you find the
ldap
section and see configuration details (such asLDAP Support enabled
), the PHP OpenLDAP extension is successfully loaded and enabled.
If you cannot find the ldap
section or see LDAP Support
as disabled, you may need to check the build configuration of that PHP version in ServBay or contact ServBay support for help. However, in most cases, the extension is already enabled by default.
Using OpenLDAP in PHP Code
Once you’ve confirmed the OpenLDAP extension is enabled, you can use PHP’s ldap_*
functions to interact with your LDAP server. The following is a basic example demonstrating how to connect to an LDAP server, perform admin binding, search for a user, and attempt user authentication.
Important note: All LDAP server addresses, ports, admin DN, passwords, search bases and filters, and user passwords in the following example are placeholders. You must replace them with your actual LDAP server configuration and credentials when implementing. Never hard-code sensitive information (like passwords) in your production code.
Sample Code: Basic Connection, Search, and Authentication
Save the following code as a PHP file (e.g. ldap_test.php
) in your ServBay website directory, and access it via your browser to run.
<?php
// --- LDAP connection configuration ---
// Replace with your LDAP server address. Use ldaps:// for secure LDAP over SSL/TLS, default port 636.
$ldapURI = "ldap://ldap.example.com:389";
// Replace with the DN (Distinguished Name) of your LDAP admin or a user with search permissions
$ldapAdminRdn = "cn=admin,dc=example,dc=com";
// Replace with the password corresponding to the admin DN above
$ldapAdminPassword = "admin_password";
// --- User search and authentication configuration ---
// Replace with the search base DN where the user resides in your LDAP directory
$searchBase = "dc=example,dc=com";
// Replace with the filter to search for a specific user. For example, searching for user with uid ‘servbay-demo’.
$searchFilter = "(uid=servbay-demo)";
// Replace with the password of the user you want to authenticate
$userPasswordToAuthenticate = "user_password_for_servbay_demo";
echo "<h2>PHP OpenLDAP Example in ServBay</h2>";
// 1. Connect to LDAP server
echo "<p>Attempting to connect to LDAP server: {$ldapURI}...</p>";
$ldapConn = ldap_connect($ldapURI);
if (!$ldapConn) {
die("<p style='color: red;'>Error: Unable to connect to the LDAP server.</p>");
}
echo "<p style='color: green;'>Successfully connected to the LDAP server.</p>";
// Set LDAP options (it’s generally recommended to set protocol version and disable referrals)
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
// 2. Bind to the LDAP server with admin credentials (for operations such as searching that require permissions)
echo "<p>Attempting to bind using admin DN '{$ldapAdminRdn}'...</p>";
if (!ldap_bind($ldapConn, $ldapAdminRdn, $ldapAdminPassword)) {
echo "<p style='color: red;'>Error: Admin bind failed.</p>";
echo "<p style='color: red;'>LDAP Error: " . ldap_error($ldapConn) . "</p>";
ldap_unbind($ldapConn); // Close the connection
die();
}
echo "<p style='color: green;'>Admin bind successful.</p>";
// 3. Search for user
echo "<p>Attempting to search in base DN '{$searchBase}' with filter '{$searchFilter}'...</p>";
$searchResult = ldap_search($ldapConn, $searchBase, $searchFilter);
if (!$searchResult) {
echo "<p style='color: red;'>Error: LDAP search failed.</p>";
echo "<p style='color: red;'>LDAP Error: " . ldap_error($ldapConn) . "</p>";
ldap_unbind($ldapConn); // Close the connection
die();
}
echo "<p style='color: green;'>Search successful.</p>";
// 4. Retrieve search result entries
$entries = ldap_get_entries($ldapConn, $searchResult);
if ($entries["count"] > 0) {
echo "<p>Found {$entries["count"]} matching entries.</p>";
// Assume we only care about the first matching user
$userDn = $entries[0]["dn"];
echo "<p>DN of the first matching user: <strong>{$userDn}</strong></p>";
// 5. Attempt to authenticate using the found user's DN and password
echo "<p>Attempting authentication bind with user DN '{$userDn}'...</p>";
// Note: This is a user bind, not an admin bind
if (@ldap_bind($ldapConn, $userDn, $userPasswordToAuthenticate)) {
echo "<p style='color: green;'>User authentication successful!</p>";
} else {
echo "<p style='color: red;'>User authentication failed.</p>";
echo "<p style='color: red;'>LDAP Error: " . ldap_error($ldapConn) . "</p>";
}
} else {
echo "<p>No users found matching filter '{$searchFilter}'.</p>";
}
// 6. Close the LDAP connection
echo "<p>Closing LDAP connection...</p>";
ldap_unbind($ldapConn);
echo "<p style='color: green;'>Connection closed.</p>";
?>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
Code Explanation
- Connection (
ldap_connect
): Establishes a connection to the LDAP server, returning a connection identifier. - Set options (
ldap_set_option
): Configures connection behavior.LDAP_OPT_PROTOCOL_VERSION, 3
sets the protocol to LDAPv3 (recommended).LDAP_OPT_REFERRALS, 0
disables referrals (usually not needed for simple applications). - Bind (
ldap_bind
): Authenticates with the LDAP server.- Anonymous bind:
ldap_bind($ldapConn)
– no DN and password, typically with limited permissions. - Authenticated bind:
ldap_bind($ldapConn, $dn, $password)
– authenticates using a specific DN and password. In this example, admin bind is performed for searching, then user bind is performed for authentication.
- Anonymous bind:
- Search (
ldap_search
): Queries directory entries under the specified base DN (searchBase
) using the provided filter (searchFilter
). - Get entries (
ldap_get_entries
): Extracts all matching entry data from the search result, returning an array of entry info. - Close connection (
ldap_unbind
): Terminates the connection and frees resources.
Notes
- LDAP Server Required: This document and example focus only on using the OpenLDAP client extension in PHP. You need to have access to an LDAP server. This could be a locally installed OpenLDAP server (managed separately from ServBay) or a remote enterprise LDAP/Active Directory server.
- Security: Always follow security best practices when handling LDAP credentials in production. Use environment variables or secure configuration files and prefer encrypted connections with LDAPS (LDAP over SSL/TLS, usually on port 636) rather than plain LDAP (port 389).
- Error Handling: The error handling in this sample is basic; in real-world applications, you should implement more robust error capture and logging.
- DN Format: The DN (Distinguished Name) format is strict and critical. Ensure your DNs exactly match your LDAP server’s configuration.
Frequently Asked Questions (FAQ)
Q: I don’t see an ldap
section in phpinfo()
, or it shows as disabled. What should I do?
A: In ServBay, the PHP OpenLDAP extension is usually enabled by default. If you encounter this issue, confirm you are looking at the correct PHP version’s phpinfo()
output. If it’s still missing, it might be an issue with your particular ServBay version or installation. Try reinstalling the PHP package in ServBay, or contact ServBay support.
Q: My PHP code reports an error: Call to undefined function ldap_connect()
.
A: This means the PHP OpenLDAP extension is not loaded or enabled. Go back to the previous section to verify its status with phpinfo()
.
Q: The extension is enabled, but connection or bind fails with an LDAP error.
A: Double-check your connection settings (server address, port) and bind credentials (DN, password) for accuracy. LDAP error messages (use ldap_error()
) usually give clues to the cause, such as “Invalid credentials” or “Can't contact LDAP server”. Make sure your LDAP server is running and the network is reachable.
Summary
ServBay offers a fast and convenient way to get PHP’s OpenLDAP extension up and running. With a quick validation step, you can ensure your PHP environment can communicate with LDAP servers. Leveraging PHP’s robust LDAP functions, developers can easily integrate user authentication and directory queries into local web applications built with ServBay, significantly expanding the range of possible application scenarios.