LDAP与PHP的要点

Ever wanted a simple way to store address book style information and network information actually next to any kind of ordered information?

是否曾经想过一种简单的方法来将地址簿样式信息和网络信息实际上存储在任何有序信息旁边?

If so, then there’s a technology which has been around since 1993, one which despite not having the cool factor of such technologies as Node.js and Go, allows you to do exactly this. It’s called LDAP!

如果是这样,那么就有一项自1993年以来就存在的技术,尽管没有Node.jsGo这样的技术的酷炫因素, 它却可以让您做到这一点。 这就是LDAP!

什么是LDAP? (What is LDAP?)

LDAP is short for Lightweight Directory Access Protocol and was developed at the University of Michigan around 1993, by Tim Howes, Steve Kille, Colin Robbins, and Wengyik Yeong.

LDAP是“ 轻型目录访问协议”的缩写,由Tim HowesSteve KilleColin RobbinsWengyik Yeong在1993年由密歇根大学开发。

In short, LDAP is an internet-ready version of an earlier protocol called X.500, which was developed back in the 80’s by the International Telecommunications Union (ITU) for managing telephone directories and directory services.

简而言之,LDAP是称为X.500的较早协议的互联网就绪版本,该协议由国际电信联盟(ITU)于80年代开发,用于管理电话簿和目录服务。

Whilst LDAP technically refers to the protocol, the name is often applied to the client and server as well. If it helps, you can think of it like SQL is for database servers; it’s the language used to interact with LDAP-enabled servers.

虽然LDAP从技术上讲是指协议,但该名称通常也适用于客户端和服务器。 如果有帮助,您可以认为它就像SQL用于数据库服务器一样。 它是与启用LDAP的服务器进行交互的语言。

There are a number of LDAP-enabled servers around, the most common of which is Microsoft’s ActiveDirectory; which has been pervasive throughout their product lineup since the release of Windows 2000.

周围有许多启用LDAP的服务器,其中最常见的是Microsoft的ActiveDirectory ; 自Windows 2000发行以来,在他们的所有产品系列中都非常普遍。

There’s an open source choice as well, one which we’ll be using throughout this article series, called OpenLDAP. It makes no assumptions as to the schema you’re using or the information you’re storing.

还有一个开源选择,在整个本系列文章中我们将使用一个开源选择,即OpenLDAP 。 它不对您使用的架构或存储的信息做任何假设。

Here in part one of the series, I’m going to:

在系列的第一部分中,我将要:

  1. Take you through the basics of setting up an OpenLDAP

    带您了解设置OpenLDAP的基础知识
  2. Show you how to load up a set of records

    向您展示如何加载一组记录
  3. Show you how to connect to it and perform some basic operations

    向您展示如何连接到它并执行一些基本操作

术语 (Terminology)

Before we do that, we need to look at a bit of the terminology. Continuing with the SQL analogy, there are a couple of terms which you’ll need to know, and which I’ll be using throughout the series, which you can find in the table below.

在此之前,我们需要先了解一些术语。 继续进行SQL类比,您需要了解几个术语,并且在整个系列中将使用这些术语,您可以在下表中找到它们。

LDAP TermDescription
dnA dn, or Distinguished Name, is a record’s unique identifier. This is much like a primary key in a relational database.
Directory Schema (or just Schema)In an LDAP directory, the entry values are governed by a directory schema. A directory schema is a set of definitions and constraints concerning the structure of the directory information.
entryAn entry is much like a record in a database, and contains attributes which store the data for the entry.
attributeAn attribute is much like an element in an associative array or column in a database. It specifies the type of information which can be stored for that attribute, along with other criteria, such as sorting and searching rules, case-sensitivity and so on.
cncn is short for common name. An example would be “John Smith”
snsn is short for surname.
LDAP术语 描述
dn dn或专有名称是记录的唯一标识符。 这很像关系数据库中的主键。
目录架构(或仅架构) 在LDAP目录中,条目值由目录架构控制。 目录架构是与目录信息的结构有关的一组定义和约束。
条目 条目非常类似于数据库中的记录,并且包含存储条目数据的属性。
属性 属性非常类似于数据库中关联数组或列中的元素。 它指定了可以为该属性存储的信息类型,以及其他标准,例如排序和搜索规则,区分大小写等。
cn cn是通用名称的缩写。 例如“约翰·史密斯”
sn是姓氏的缩写。

The terminology is quite sophisticated, so I’m unable to cover it all here. But hopefully these basics are enough to get you started.

该术语非常复杂,因此我无法在此处进行介绍。 但是希望这些基础知识足以使您入门。

For more detailed information, check out this guide from O’Reilly, or the LDAP entry on Wikipedia.

有关更多详细信息,请参阅O'Reilly的本指南Wikipedia上的LDAP条目

安装LDAP服务器 (Installing An LDAP Server)

I’ve never found installing and configuring OpenLDAP particularly straight-forward and a lot of the information available on the net can be misleading or be for a mixture of versions of the server. Here is my best, most concise set of steps, based on using a Debian-based server.

我从未发现特别简单明了地安装和配置OpenLDAP,并且网络上的许多可用信息可能会引起误解,也可能会混用服务器的各种版本。 基于使用基于Debian的服务器 ,这是我最好,最简洁的一组步骤。

Firstly, install the core server and utils by running the following commands:

首先,通过运行以下命令来安装核心服务器和实用程序:

sudo apt-get install slapd ldap-utils

These commands will ask you a set of questions, install the server, along with setting it to start at boot time. After it’s done, run the following command, which will help us better configure the installation:

这些命令将询问您一系列问题,安装服务器以及将其设置为在引导时启动。 完成后,运行以下命令,这将帮助我们更好地配置安装:

dpkg-reconfigure slapd

This will ask a series of questions, and here’s a guide to answering them:

这将提出一系列问题,这是回答这些问题的指南:

  • Omit OpenLDAP server configuration? No

    省略OpenLDAP服务器配置? 没有

  • DNS domain name: homestead.localdomain

    DNS域名: homestead.localdomain

  • Name of your organization: … Whatever & Co

    您的组织名称: …随便

  • Admin Password:

    管理员密码:

  • Confirm Password:

    确认密码:

  • OK

  • BDB

    银行
  • Do you want your database to be removed when slapd is purged? No

    您是否希望在清除slapd后删除数据库? 没有

  • Move old database? Yes

    移动旧数据库?

  • Allow LDAPv2 Protocol? No

    允许LDAPv2协议? 没有

验证安装 (Verify the Installation)

With that done, let’s quickly verify that everything’s working, by running the following command:

完成此操作后,我们通过运行以下命令来快速验证一切是否正常:

ldapsearch -x -b dc=homestead,dc=localdomain

You shouldn’t receive an error, but if so, make sure that OpenLDAP’s running; you can do this by running the following command:

您不应该收到错误,但是如果是这样,请确保OpenLDAP正在运行;否则,请执行以下步骤。 您可以通过运行以下命令来执行此操作:

sudo netstat -tlnp | grep slapd

You should see output such as the following (formatted for readability):

您应该看到如下输出(为便于阅读而格式化):

tcp    0   0 0.0.0.0:389  0.0.0.0:*    LISTEN    6556/slapd      
tcp6   0   0 :::389       :::*         LISTEN    6556/slapd

填充数据库 (Populating The Database)

Now that the server is set up, we need to load it up with data. Create a new file called users.ldif and in it, add the following records:

现在服务器已经设置好了,我们需要用数据加载它。 创建一个名为users.ldif的新文件,并在其中添加以下记录:

dn: cn=Sheldon Cooper,ou=People,dc=homestead,dc=localdomain
cn: Sheldon Cooper
objectClass: person
objectClass: inetOrgPerson
sn: Cooper

dn: cn=Leonard Hofstadter,ou=People,dc=homestead,dc=localdomain
cn: Leonard Hofstadter
objectClass: person
objectClass: inetOrgPerson
sn: Hofstadter

dn: cn=Howard Wolowitz,ou=People,dc=homestead,dc=localdomain
cn: Howard Wolowitz
objectClass: person
objectClass: inetOrgPerson
sn: Wolowitz

dn: cn=Rajesh Koothrappali,ou=People,dc=homestead,dc=localdomain
cn: Rasjesh Koothrappali
objectClass: person
objectClass: inetOrgPerson
sn: Koothrappali

With the file saved, run the following command to load the information into the database:

保存文件后,运行以下命令将信息加载到数据库中:

ldapadd -x -W -D "cn=admin,dc=homestead,dc=localdomain" -f users.ldif

This will prompt you for the password you set earlier. Enter it and you should see output like the following:

这将提示您输入先前设置的密码。 输入它,您应该看到如下输出:

adding new entry "cn=Sheldon Cooper,ou=People,dc=homestead,dc=localdomain"

adding new entry "cn=Leonard Hofstadter,ou=People,dc=homestead,dc=localdomain"

adding new entry "cn=Howard Wolowitz,ou=People,dc=homestead,dc=localdomain"

adding new entry "cn=Rajesh Koothrappali,ou=People,dc=homestead,dc=localdomain"

验证记录是否存在 (Verify the Records are Present)

Now let’s do a quick check that the records are available. From the command line, run:

现在,让我们快速检查一下记录是否可用。 从命令行运行:

ldapsearch -x -b "dc=homestead,dc=localdomain" -s sub "objectclass=*"

This should display output similar to the following, which I’ve truncated for the purposes of readability:

这应该显示类似于以下的输出,出于可读性考虑,我将其截断了:

# extended LDIF
#
# LDAPv3
# base <dc=homestead,dc=localdomain> with scope subtree
# filter: objectclass=*
# requesting: ALL
#

# homestead.localdomain
dn: dc=homestead,dc=localdomain
objectClass: top
objectClass: dcObject
objectClass: organization
o: homestead
dc: homestead

与PHP交互 (Interacting with PHP)

With all these steps completed, we’re now ready to use PHP to query the server. To keep things simple, we’re using the Zend-Ldap component from Zend Framework 2.

完成所有这些步骤后,我们现在可以使用PHP查询服务器了。 为了简单起见 ,我们使用Zend Framework 2中的Zend-Ldap组件

There are a number of PHP LDAP libraries available, but this was the one that I found most effective and straight-forward to use. Granted, I am a bit of a Zend Framework evangelist, but this honestly is the simplest library I’ve found.

有许多可用PHP LDAP库 ,但这是我发现最有效且直接使用的库。 当然,我有点像Zend Framework的传播者,但这实际上是我找到的最简单的库。

To handle the dependency, as in almost all PHP projects these days, we’ll use Composer to make it available. In your project directory, create a composer.json file, as below.

为了处理这种依赖关系,就像现在几乎所有PHP项目一样,我们将使用Composer使其可用。 在您的项目目录中,创建一个composer.json文件,如下所示。

{
    "require": {
        "php": ">=5.3.0",
        "zendframework/zend-ldap": "2.3.*@dev"
    }
}

After that, run composer install to create the vendor directory and bring in the dependency.

之后,运行composer install创建供应商目录并引入依赖关系。

连接到LDAP服务器 (Connecting to the LDAP server)

With that done, create a new file called index.php in the root of your project directory; in there add the code below:

完成后,在项目目录的根目录中创建一个名为index.php的新文件。 在其中添加以下代码:

<?php
require 'vendor/autoload.php';

$baseDn = 'dc=homestead,dc=localdomain';
$options = array(
    'host' => '192.168.10.10',
    'password' => 'homestead',
    'bindRequiresDn' => true,
    'baseDn' => 'dc=homestead,dc=localdomain',
    'username' => "cn=admin,$baseDn"
);
$ldap = new Zend\Ldap\Ldap($options);
$ldap->bind();

This will first make the Zend\Ldap available via the composer generated autoload file. I’ve next defined a variable, $baseDn, to keep the code that much more readable here in the article.

首先,将通过作曲家生成的自动加载文件使Zend\Ldap可用。 接下来,我定义了一个变量$baseDn ,以使代码在本文中更具可读性。

Next I’ve created an array called $options, which stores the configuration settings we’ll use for initializing the Zend\Ldap\Ldap object.

接下来,我创建了一个名为$options的数组,该数组存储用于初始化Zend\Ldap\Ldap对象的配置设置。

In it I’ve specified the hostname, password, basedn and username. We could have skipped the username and password, but as we’ll be performing authenticated operations, it’s simplest to add it all now.

在其中,我指定了主机名密码basedn用户名 。 我们本可以跳过用户名和密码,但是由于我们将执行经过身份验证的操作,因此现在将其全部添加是最简单的。

With the new Zend\Ldap\Ldap object initialized, I then called the bind method to make the connection to the server.

初始化了新的Zend\Ldap\Ldap对象后,我随后调用bind方法建立与服务器的连接。

搜索数据库 (Searching The Database)

Now let’s perform the first and simplest operation on the LDAP server: searching. The code below will search for every record in ou=People,dc=homestead,dc=localdomain, which will return the four we loaded earlier.

现在,让我们在LDAP服务器上执行第一个也是最简单的操作:搜索。 下面的代码将搜索ou=People,dc=homestead,dc=localdomain每个记录,这将返回我们之前加载的四个记录。

The first argument, (objectclass=*) specifies an SQL-like filter. This equates to running a SELECT *. The final argument performs a search which will look for all records.

第一个参数(objectclass=*)指定类似SQL的过滤器。 这等同于运行SELECT * 。 最后一个参数执行搜索,查找所有记录。

There are a number of different search types, which we’ll cover in the next article. For now, this type is sufficient for our needs.

有许多不同的搜索类型,我们将在下一篇文章中介绍。 目前,这种类型已经足够满足我们的需求。

$result = $ldap->search(
   '(objectclass=*)',
   "ou=People,$baseDn",
   Zend\Ldap\Ldap::SEARCH_SCOPE_SUB
);

Next, we’ll iterate over the records in two ways. Firstly, we’ll call the toArray() method on the $result object, which we pass to json_encode. I’ve done this as a simple way of displaying all the information available.

接下来,我们将以两种方式遍历记录。 首先,我们将在$result对象上调用toArray()方法,该方法将传递给json_encode 。 我这样做是一种显示所有可用信息的简单方法。

print json_encode($result->toArray());

Alternatively, we could iterate over the dataset using a foreach as below. In this example, we’ve displayed the dn and cn elements of each record.

另外,我们可以使用下面的foreach遍历数据集。 在此示例中,我们显示了每个记录的dncn元素。

foreach ($result as $item) {
    echo $item["dn"] . ': ' . $item['cn'][0] . '<br />';
}

更新条目 (Updating an Entry)

Now that we’ve looked at basic record searching and iteration, let’s look at updating a record. This requires three steps:

现在,我们已经研究了基本的记录搜索和迭代,现在让我们来看一下更新记录。 这需要三个步骤:

  1. Fetching the record

    取得记录
  2. Updating an existing property or setting a new one

    更新现有资产或设置新资产
  3. Persisting the record back to the LDAP server

    将记录持久化回LDAP服务器
$hm = $ldap->getEntry(
    "cn=Rajesh Koothrappali,ou=People,$baseDn"
);
Zend\Ldap\Attribute::setAttribute(
    $hm, 'mail', 'koothrappalir@homestead.localdomain'
);
$ldap->update(
    "cn=Rajesh Koothrappali,ou=People,$baseDn", $hm
);

In the code above, we’ve retrieved an entry by calling the getEntry method, passing in the record dn. We next called the setAttribute() method, specifying the record object, the property we want to set, then the value of the property.

在上面的代码中,我们通过调用getEntry方法并传入记录dn检索条目。 接下来,我们调用setAttribute()方法,指定记录对象,要设置的属性,然后指定属性的值。

Finally, we called the update() method, passion in the record dn and the record object. All being well, the record will be updated.

最后,我们调用了update()方法,对记录dn和记录对象进行了设置。 一切顺利,该记录将被更新。

删除条目 (Deleting an Entry)

Now that we can search and update records, let’s finish up by stepping through deleting a record. To do this, we call the delete method, passing in the dn of the record we want to delete.

现在我们可以搜索和更新记录了,让我们通过逐步删除记录来结束。 为此,我们调用delete方法,传入要删除的记录的dn

As the operation could fail, in this example I’ve wrapped the call in a try/catch block, which catches an LdapException if thrown and prints out the reason for the failure.

由于该操作可能失败,因此在此示例中,我将该调用包装在try / catch块中,该块在抛出LdapException时捕获LdapException并打印出失败原因。

There could be a variety of reasons for the exception to be thrown, such as the record not existing and the user we’ve authenticated as not having sufficient permission.

引发异常的原因可能有多种,例如记录不存在以及我们已认证为没有足够权限的用户。

try {
    $ldap->delete("cn=Hans Meier,ou=People,$baseDn");
} catch (\Zend\Ldap\Exception\LdapException $e) {
    print $e->getMessage();
}

结语 (Wrapping Up)

And that’s how to set up and interact with an LDAP server – specifically OpenLDAP – in PHP. I hope you’ve enjoyed this quick run through of how to do it. In the next article, we’ll be exploring LDAP in further depth by:

这就是在PHP中设置LDAP服务器并与之交互的方法,特别是OpenLDAP。 我希望您喜欢如何快速完成此操作。 在下一篇文章中,我们将通过以下方式进一步探讨LDAP:

  • Performing more complicated searches

    执行更复杂的搜索
  • Inserting records

    插入记录
  • Moving records

    移动记录
  • Making secure connections

    建立安全连接

If you’d like more information on what we’ve covered today, there’s a host of links in the further reading section which should satisfy your curiosity.

如果您想了解我们今天所涵盖的内容的更多信息,请在进一步阅读部分中找到许多链接,这些链接应该可以满足您的好奇心。

进一步阅读 (Further Reading)

翻译自: https://www.sitepoint.com/essentials-ldap-php/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值