loading...

Setup PHP development environment width LDAP

ko31 profile image Ko Takagi ・2 min read

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.

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>
Enter fullscreen mode Exit fullscreen mode

Create and start containers.

cd <my-project-name>
docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

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.

Alt Text

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.

Alt Text

You can see that you were able to logged as an admin user.

Alt Text

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.');
}
Enter fullscreen mode Exit fullscreen mode

You can confirm a successful connection at http://localhost:8000/connect.php

Alt Text

Have fun!πŸ‘

Discussion

pic
Editor guide
Collapse
saboorhamedi profile image
saboor

Great, this is my first time, I join this community.

Collapse
ko31 profile image