Adressbook of «YourMegaCompanyName»

Создаём WEB адресный справочник PHP + LDAP

Так случилось, что у (относительно) большой кампании было много отдалённых офисов, в которых находилось приличное количество пользователей. Все офисы соединены в одну сеть с общим доменом, каждый офис был определён в Active Directory (далее по тексту AD) как Organization Unit (OU), в котором уже заводились пользователи.

Необходимо было дать пользователям возможность быстро и без особенных усилий получать контактные данные необходимого сотрудника из AD, а системных администраторов освободить от рутины редактирования текстового файла, который играл роль адресной книги.

Готовых подходящих вариантов для решения поставленной задачи не нашлось, поэтому пришлось делать всё своими руками и головой.

Начнём с того, что для начала нужно определиться что использовать, это просто — итоговый справочник должен быть доступен всем пользователям домена посредством браузера. Первое, что приходит на ум это PHP в связке с ldap, их и будем использовать. Большим плюсом использования PHP я считаю его относительную простоту — любой хоть немного понимающий системный администратор сможет внести, при необходимости, нужные правки в код, не особенно напрягаясь.

Итак, начнём. для начала зададим параметры подключения к домену:

$srv ="SERVER"; $srv_domain ="DOMAIN.COM"; $srv_login ="USERNAME@".$srv_domain; $srv_password ="PASSWORD"; 

Переменная $doscript нужна для того, чтобы хранить значение — определили ли мы OU, в котором будем искать пользователей или нет. Если не нашлось совпадений, перечисленных в «switch-case», то $doscript=false, главная часть скрипта выполняться не будет, а будет выведена стартовая страница «main_table.html» (о ней расскажу в самом конце).

Читайте также:  contact form

Если же мы определили OU, тогда приступаем к дальнейшим действиям: начинаем рисовать пользователю страницу справочника:

Включаем стили для более приятного внешнего вида (да, их можно было подключить как css-файл, однако некоторые версии IE не хотят воспринимать стили, заданные таким образом, поэтому приходится писать прямо в скрипт):

 * a a:hover #bold #table,tr,td /* Нечетные строки */#table tbody tr:nth-child(odd) /* Четные строки */ #table tbody tr:nth-child(even) #noborder #sp30px #smallsize #top #top:hover .smalltext .smalltext:hover .transition-rotate .transition-rotate:hover #lineheight 

Со стилями покончено, теперь пишем заголовок вкладки и рисуем удобную ссылку возврата на главную страницу:

Определяем поисковые фильтры по AD, и получаем данные об OU:

$filter ="(&(objectcategory=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"; //все пользователи, кроме отключенных. $filter2 ="(objectCategory=OrganizationalUnit)"; // для получения информации о OU $ds=ldap_connect($srv); if ($ds) < $r=ldap_bind($ds,$srv_login,$srv_password);; ldap_set_option($ds,LDAP_OPT_REFERRALS, 0); ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3); $sr=ldap_search($ds,$dn ,$filter ); ldap_sort($ds,$sr, "givenname"); $info = ldap_get_entries($ds, $sr); $sr2=ldap_search($ds,$dn ,$filter2 ); $placeinfo = ldap_get_entries($ds, $sr2); $PlaceName = $placeinfo[0]["l"][0]; // name of place $PlaceAddres = $placeinfo[0]["street"][0]; // address of place $PlaceMail = $placeinfo[0]["description"][0]; // mail of place $PlacePhone = $placeinfo[0]["st"][0]; // phone of plase 

Далее оформляем верхнюю часть страницы:

Далее получаем в цикле и обрабатываем данные пользователей, при этом, чтобы скрыть некоторые (например служебные) учётные записи, просто прописываем «hide» в поле «комната» в реквизитах пользователя в AD, такие пользователи не будут отображаться в справочнике:

Кстати, если вам потребуется получить значение другого атрибута, то помните (это важно):
в запросе передаём имя атрибута строчными буквами, иначе не заработает.

И вставляем полученные данные в таблицу:

 echo " ". $n+=1 ." ". $UserName ." 
". $UserPosition ."
"; // Имя пользователя и должность if ($UserMail !='-') echo "
$UserMail
"; // если у пользователя есть e-mail создаём ссылку на отправку письма else echo "-"; //если нет e-mail - ставим прочерк. echo " ". $UserIpPhone ." ". $UserMobile ." "; > > echo "";

Далее мы закрываем подключение по ldap, или выводим сообщение о невозможности подключения к серверу:

ldap_close($ds); > else echo "

Unable to connect to LDAP server

"; echo '
';>

Файл «main_table.html» изнутри себя представляет простую html страницу с ссылками, и выглядит примерно так:

     
Places and offices

OU1
OU2

Если кому-либо поможет мой код — я буду рад, пользуйтесь!

Также можете свободно редактировать его как вам угодно (улучшать/ухудшать) и распространять любыми методами.

Источник

What is LDAP PHP?

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access “Directory Servers”. The Directory is a special kind of database that holds information in a tree structure.

How configure LDAP in PHP?

  1. apt-get install php7. 0-ldap (or use apt-get install php7. 1-ldap )
  2. service apache2 restart.
  3. After that create a php file to get the php configuration phpinfo();
  4. Now ldap is installed.

How do I connect to LDAP server?

  1. Log in to the IBM® Cloud Pak for Data web client as an administrator.
  2. From the menu, click Administer > Manage users.
  3. Go to the Users tab.
  4. Click Connect to LDAP server.
  5. Specify which LDAP authentication method you want to use:
  6. In the LDAP port field, enter the port that you are connecting to.

How can I tell if PHP supports LDAP?

You can try and check it with extension_loaded() like this: $builtWithLdap = extension_loaded(‘ldap’); or alternativly as a crowbar approach, just check if one of the functions exists: $builtWithLdap = function_exists(‘ldap_add’);

What is a LDAP server used for?

LDAP (Lightweight Directory Access Protocol) is an open and cross platform protocol used for directory services authentication. LDAP provides the communication language that applications use to communicate with other directory services servers.

What is an LDAP bind?

LDAP bind requests provide the ability to use either simple or SASL authentication. In simple authentication, the account to authenticate is identified by the DN of the entry for that account, and the proof identity comes in the form of a password.

How enable LDAP support in PHP?

LDAP support in PHP is not enabled by default. You will need to use the –with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory. To enable SASL support, be sure –with-ldap-sasl[=DIR] is used, and that sasl.

How do I create a LDAP server?

  1. Server type. Select the type of LDAP server you are using.
  2. Security options. Data can be passed between the MSS Administrative Server and the LDAP server as clear text or encrypted.
  3. Server name. Enter the LDAP server name as either a name or a full IP address.
  4. Server port.
  5. Username and Password.

How do I find my LDAP server details?

  1. In the Start menu, search for “cmd”
  2. Right click on Command Prompt and select Run as Administrator.
  3. The servers Command Prompt will open, in the prompt run dsquery * C:\Users\Administrator>dsquery *
  4. The first output displayed is your Base DN:

Why LDAP is faster than database?

Here’s the difference between the two: LDAP is highly optomized for reads, it can do them much faster than your MySQL database can, so it will scale much better than your database solution will in the long run which is optomized for reads and writes.

Is LDAP same as SSO?

The difference that can be talked about when looking at these two applications is that LDAP is an application protocol that is used to crosscheck information on the server end. SSO, on the other hand, is a user authentication process, with the user providing access to multiple systems.

What is LDAP vs Ldaps?

What is LDAP and LDAPS? LDAP (Lightweight Directory Application Protocol) and Secure LDAP (LDAPS) is the connection protocol used between Mimecast and the Network Directory or Domain Controller within the customer’s infrastructure. LDAP transmits communications in Clear Text, and LDAPS communication is encrypted.

Источник

Active Directory Using LDAP In PHP Or Laravel

active directory using ldap in php or laravel

In this article, we will learn Active Directory implementation using LDAP in PHP or Laravel. LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access “Directory Servers”. The Directory is a special kind of database that holds information in a tree structure. Let’s see the overview and then implement it with an example.

What Is Active Directory In Simpler Word?

In a very simpler word, Active Directory (AD) is a directory service developed by Microsoft for Windows domain networks. It is used to authenticate and authorize users and computers, it allows management and storage of information in a network.

Let’s understand the Active Directory, for example, you have 100 offices and all the 100 offices have a large number of employees. So to manage each & every employee you have the systems in each offices to track different records.

The employee can log in to the system and can see the different activities they have done and they will do in the future. So instead of managing all the records from individual offices, you will create a central(main) system from where every data can be managed structurally and shared among all the offices. That central system’s records are called Active Directory.

Why Active Directory(AD) Or LDAP Required?

There are lots of reasons to use Active Directory. It can vary from person to person but some of them are below.

  1. The client always demanding performance in large-scale projects so that AD is used for performance enhancement.
  2. Suppose, Clients have thousands of websites and they have lots of registered users. So that by using AD or LDAP they can store all the user information in a single place. So just by a single query, they can easily authenticate.
  3. A third and most important reason for using AD or LDAP. For security reasons, they can use AD or LDAP. This is the most secure way to protect user’s information in a single place. LDAP can work with SSL & TLS and thus can be used for.
  4. LDAP’s main usage is to provide faster retrieval of the data. It acts as a central repository for storing user details that can be accessed by various applications at the same time.
  5. LDAP apart from supporting the data recovery capability. Also, allows us to export data into an LDIF file that can be read by various software available in the market.
  6. Active Directory helps you to organize your company’s users, computers, and more. Your IT administrator uses the AD to organize your company’s complete hierarchy from which computers belong to which network, to what your profile picture looks like or which users have access to the storage room.

LDAP Terminology

LDAP Terminology is the most important thing that needs to understand before LDAP implementation.

  • DN: DN stands for the Distinguish Name. DN is used to uniquely identify entry into the Active Directory. For example, uid=john.doe
  • DC: DC stands for the Domain Component. As the name suggests, it is used to identify the Domain Name. For example, www.scratchcode.io would be written as DC=www, DC=scratchcode, DC=io
  • OU: OU stands for the Organizational Unit. OU is also called user group. I can also call like the user is part of it like Any University, Any Degree, Any City, etc. For example, OU=USA, OU=Doctor, OU=California.
  • CN: CN stands for the Common Name. If you want to query for the individual object then this will be used like Persons Name, Persons Mobile Number, etc.

Free LDAP Test Server For Testing

If you have a question in your mind that is there any free LDAP test server? so that you can easily test LDAP functionality. There are lots of websites providing free LDAP service for only testing. This is only for testing while your clients providing you with all the details for LDAP or AD. Check free LDAP test server

LDAP Server Information (read-only access):

Server: ldap.forumsys.comPort: 389
Bind DN: cn=read-only-admin,dc=example,dc=com
Bind Password: passwordou=mathematicians,dc=example,dc=comou=scientists,dc=example,dc=com

You can use followings uid for the uniquely identified user.

Example Of Active Directory Implementation Using LDAP in PHP or Laravel

Notes: You need to enable LDAP extension in php.ini file so that it will start working otherwise it will throw an error.

Notes: I recommended you to test this script on the live server instead of local because there are lots of issues on the local server.

Get more information about the LDAP functions from here.

Additionally, read our guide:

  1. Best Way to Remove Public from URL in Laravel
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. How To Find Duplicate Records in Database

That’s it for now. We hope this article helped you to learn Active Directory Implementation Using LDAP in PHP or Laravel

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. 🙂 Keep Smiling! Happy Coding!

Источник

Оцените статью