I have created a system to authenticate LDAP from PHP before.
At that time, I created a development environment with Docker, so I'll make a note of how to set it up.
The environment I used is as follows.
- macOS Catalina 10.15.5
- Git
- Docker Desktop for Mac
How to setup
open a terminal and clone LAMP+OpenLDAP Dev Docker repository.
git clone https://github.com/ko31/lamp-dev-docker.git <your-project-name>
Create and start containers.
cd <my-project-name>
docker-compose up -d
Then, you can access your local website at http://localhost:8000
(The document root is the <your-project-name>/www/html
directory.)
Try connecting to LDAP from PHP
To begin, make sure you have users connecting to your LDAP server.
Open phpLDAPadmin at http://localhost:8888 and click login
.
In this container, the Login DN is cn=admin,dc=example,dc=com
and the Password is password
by default. Input it and click authenticate
.
You can see that you were able to logged as an admin
user.
Create <your-project-name>/www/html/connect.php
and put the following:
<?php
// LDAP settings
const LDAP_HOST = "ldap-host";
const LDAP_PORT = 389;
const LDAP_DC = "dc=example,dc=com";
const LDAP_CN = "admin";
const LDAP_PASS = "password";
// Connect LDAP server.
$ldap_conn = ldap_connect(LDAP_HOST, LDAP_PORT);
if (!$ldap_conn) {
exit('Could not connect to LDAP server.');
}
// Switch protocol to LDAPv3.
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
// Bind to LDAP directory.
$ldap_dn = 'cn=' . LDAP_CN . ',' . LDAP_DC;
$ldap_bind = ldap_bind($ldap_conn, $ldap_dn ,LDAP_PASS);
if ($ldap_bind) {
exit('LDAP bind successful..');
} else {
exit('LDAP bind failed.');
}
You can confirm a successful connection at http://localhost:8000/connect.php
Have fun!👍
Top comments (4)
Light weight Active Directory allow to connect your account using PHP. Please follow these steps to access this library. theknowledgeadda.com/how-to-connec...
Thank you for sharing!
Great, this is my first time, I join this community.
Thanks!