PHP Connection LDAP server

Source: Internet
Author: User
Tags format anonymous array bind empty html form connect sort
Server "Summary" The most basic form of LDAP is a standard way to connect to a database. The database is optimized for read queries. So it can get the results of the query quickly, but in other ways, such as updates, it's much slower.

This article demonstrates how to use PHP to connect to an LDAP server. A specific example is to connect to a common LDAP server and search. This example simulates the Netscape Communicator 4.*, which connects to the LDAP resource through its own address book.

LDAP Introduction

Many people may have heard of LDAP, but have no idea what it is and how it works. I will not introduce LDAP in detail here, just a brief introduction to the protocol.

LDAP is a protocol used to publish directory information to many different resources. Usually it is used as a centralized address book, but it can be more powerful depending on the needs of the organizer.

The most basic form of LDAP is a standard way to connect to a database. The database is optimized for read queries. So it can get the results of the query quickly, but in other ways, such as updates, it's much slower. It is particularly noteworthy that LDAP is typically used as a hierarchal database rather than as a relational database. Therefore, its structure is better represented by a tree than by a table. Because of this, you cannot use SQL statements.

In short, LDAP is a quick way to get centralized, static data about people or resources.

Requirements

Phpv.4 (Previous versions can be, but not tested), compiled to support LADP, that is, the use of compile-time with--WITH-LDAP public LDAP directory. In the example, two were provided.

Example overview

1. Set up information for the public LDAP server
2. Create an LDAP query
3. Connecting to an LDAP server
4. If the connection succeeds, process the query
5. Formatted output
6. Close the connection
7. Design the HTML form of the search interface
8. Display Results

Setting up information for public LDAP servers

The first thing we need to do is define all the LDAP servers we want to search for.

"Ldap_name" = Name of the new LDAP project
"Ldap_server" = IP address or host name of the new LDAP project
"LDAP_ROOT_DN" = Distinguished name of the root of the new LDAP project

? Php

$LDAP _name[0] = "Netscape Net Center";
$LDAP _server[0] = "memberdir.netscape.com";
$LDAP _root_dn[0] = "ou=member_directory,o=netcenter.com";

$LDAP _name[1] = "Bigfoot";
$LDAP _server[1] = "ldap.bigfoot.com";
$LDAP _root_dn[1] = "";


Set it to 0 if no server is selected
if (! $SERVER _id)
$SERVER _id=0;

? >

Establishing an LDAP query

As mentioned earlier, LDAP queries are not the same as SQL queries. Therefore, the statement is subject to a certain limit, the following is a basic example.

Create Query $ldap _query = "cn= $common";

In our example, "CN" is the property we want to search, and $common is the string variable obtained from the search form. The LDAP query statement statement can use the wildcard character ' * '. For example, ' $stanley ' will be able to find ' Dan Stanley '.

Connecting to an LDAP server

The following function connects to an LDAP resource and assigns the connection's identification number to a variable as if it were connected to a common database, such as MySQL.

? Php

Connecting to LDAP
$connect _id = ldap_connect ($LDAP _server[$SERVER _id]);

? >

In our example, "$connect _id" is the identification number of the connection, $LDAP _server is an array of possible LDAP servers, and $server_id is the LDAP server variable that is obtained from the search form.

If the connection succeeds, process the query

If the connection is successful, we will get a valid LDAP connection identification number so that we can process the query.

? Php
if ($connect _id)
{
Certification
$bind _id = ldap_bind ($connect _id);

Perform a search
$search _id = Ldap_search ($connect _id, $LDAP _root_dn[$SERVER _id], $ldap _query);

To assign a result collection to an array
$result _array = ldap_get_entries ($connect _id, $search _id);
}
Else
{
Show Connection Errors
echo "Could not connect to LDAP server: $LDAP _server[$SERVER _id]";
}

? >

Once we have established a connection with the LDAP server, we must authenticate. When you connect to most databases, PHP does this by sending a username and password. However, in LDAP, authentication is unknown until a bind operation is performed. In our example, "$bind _id" is an identifier for a bound connection. We are bound to the public LDAP server by anonymous. Therefore, when executing ldap_bind (), only the connection identification number is used, and no other parameters are required.

After being authenticated (this is anonymous), we can use the Ldap_search () function to execute the query, resulting in the $search_id of the connection identifier we are searching for.

We then use the Ldap_get_entries () function to assign the result set to the $result_array variable. This allows us to arrange the information logically so that it can be displayed.

Format output

After performing an LDAP search, the returned data is sorted in the order in which they were searched. However, we do not have the SQL so convenient in the sort, we can use the order by statement. Typically, most public LDAP directories do not have a standard size specification. Sorting is a character-based ASCII value, we must format the characters in lowercase to output in alphabetical order.

It is particularly noteworthy that the returned LDAP result set is a multidimensional array. Therefore, the structure of the $result_array in our script is as follows:

$result _array[0]["cn"] [0] = "Dannie Stanley"
["DN"] [0] = "uid=dannie,dc=spinweb.net"
["givenname"] [0] = "Dannie"
["SN"] [0] = "Stanley"
["Mail"] [0] = "danSPAM@spinweb.net"
$result _array[1]["cn"] [0] = "Michael Reynolds"
["DN"] [0] = "uid=michael,dc=spinweb.net"
["givenname"] [0] = "Michael"
["SN"] [0] = "Reynolds"
["Mail"] [0] = "michaelSPAM@spinweb.net"

The reason data is stored in this format is that each attribute may have more than one value (like the structure of a tree). For example, if my name is ' Dannie ', I can also add some attributes to LDAP, such as:

$result _array[0]["cn"] [0] = "Dannie Stanley"
["DN"] [0] = "uid=dannie,dc=spinweb.net"
["givenname"] [0] = "Dannie"
["givenname"] [0] = "Dan"
["SN"] [0] = "Stanley"
["Mail"] [0] = "danSPAM@spinweb.net"

In our search, we only care about the first value of each attribute, so we only use a value of 0 for each attribute except for the DN. Here's a simple list of attributes and their meanings:

"cn" = Common Name
"DN" = Distinguished Name
"Givenname" = Name
"SN" = Last Name
"Mail" = Email address


? Php

If the search succeeds, sort the results
if ($result _array)
{
for ($i =0; $i
{
$format _array[$i][0] = strtolower ($result _array[$i] ["cn"][0]);
$format _array[$i][1] = $result _array[$i] ["DN"];
$format _array[$i][2] = strtolower ($result _array[$i] ["givenname"][0]);
$format _array[$i][3] = strtolower ($result _array[$i] ["SN"][0]);
$format _array[$i][4] = strtolower ($result _array[$i] ["Mail"][0]);
}

Sort array
Sort ($format _array, "sort_string");

for ($i =0; $i
{
$CN = $format _array[$i][0];
$DN = $format _array[$i][1];
$fname = Ucwords ($format _array[$i][2]);
$lname = Ucwords ($format _array[$i][3]);
$email = $format _array[$i][4];

if ($dn && $fname && $lname && $email)
{
$result _list. = "$fname $lname";
$result _list. = "<$email>
\ n ";
}
ElseIf ($dn && $cn && $email)
{
$result _list. = "<a Href= '/" ldap://$LDAP _server[$SERVER _id]/$dn/"' $cn </A>";
$result _list. = "<a Href= '/" mailto: $email/"' > $email </A>
\ n ";
}
}
}
Else
{
echo "Result set empty for query: $ldap _query";
}


? >

In our example, the $format _array is the new array we created, which includes the results of the query and is formatted as output. First loops each element in the $result_array and assigns it to a two-d array for sorting. We also use the Strtolower () function to change all the values to lowercase.

Next, we use a function called sort () from PHP to sort. The first parameter is the array to sort, and the other is the sort type to perform, which is defined by the PHP document. As we sort by string, we use "sort_string".

Third, we loop through the formatted array and assign it to an output character named $result_list, which contains the HTML description. In particular, in the hyperlinks, I use the LDAP URL format. Examples of this format are similar: href= "Ldap://ldap.domain.net/uid=dannie,dc=domain.net".

Close connection

Now that all of our data has been included in the $result_list, we can safely turn off the LDAP connection.

? Php

Close connection
Ldap_close ($connect _id);

? >

HTML table for custom search interface

Finally, we want to customize the HTML table for the search, which is used to perform the search for the user.

Custom Form
echo "

echo "Search in: echo "; echo "
";
echo "Search for: echo " ";
echo " ";

? >

The $php_self in the code is a global constant that represents the script page itself, where the loop is used to create the Select option from our $ldap_name variable.

Show results

Now that all the work has been done, we will print out the result set. If no results are met, the information "no Results" will be displayed.

? Php

Show results
if ($result _list)
{
echo "


Bgcolor=\ "#FFFFEA \" width=\ "450\" >
$result _list
;
}
Else
echo "No Results";


? >

Source

Here's the complete source code, just cut and paste it into an HTML document, and you can try it.

? Php

$LDAP _name[0] = "Netscape Net Center";
$LDAP _server[0] = "memberdir.netscape.com";
$LDAP _root_dn[0] = "ou=member_directory,o=netcenter.com";

$LDAP _name[1] = "Bigfoot";
$LDAP _server[1] = "ldap.bigfoot.com";
$LDAP _root_dn[1] = "";

Set it to 0 if no server is selected
if (! $SERVER _id)
$SERVER _id=0;

Create a query
$ldap _query = "cn= $common";

Connecting to LDAP
$connect _id = ldap_connect ($LDAP _server[$SERVER _id]);

if ($connect _id)
{
Certification
$bind _id = ldap_bind ($connect _id);

Perform a search
$search _id = Ldap_search ($connect _id, $LDAP _root_dn[$SERVER _id], $ldap _query);

To assign a result collection to an array
$result _array = ldap_get_entries ($connect _id, $search _id);
}
Else
{
Show Connection Errors
echo "Could not connect to LDAP server: $LDAP _server[$SERVER _id]";
}

If the search succeeds, sort the results
if ($result _array)
{
for ($i =0; $i
{
$format _array[$i][0] = strtolower ($result _array[$i] ["cn"][0]);
$format _array[$i][1] = $result _array[$i] ["DN"];
$format _array[$i][2] = strtolower ($result _array[$i] ["givenname"][0]);
$format _array[$i][3] = strtolower ($result _array[$i] ["SN"][0]);
$format _array[$i][4] = strtolower ($result _array[$i] ["Mail"][0]);
}

Sort array
Sort ($format _array, "sort_string");

for ($i =0; $i
{
$CN = $format _array[$i][0];
$DN = $format _array[$i][1];
$fname = Ucwords ($format _array[$i][2]);
$lname = Ucwords ($format _array[$i][3]);
$email = $format _array[$i][4];

if ($dn && $fname && $lname && $email)
{
$result _list. = "<a Href= '/" ldap://$LDAP _server[$SERVER _id]/$dn/"' $fname $lname </A>";
$result _list. = "<$email>
\ n ";
}
ElseIf ($dn && $cn && $email)
{
$result _list. = "<a Href= '/" ldap://$LDAP _server[$SERVER _id]/$dn/"' $cn </A>";
$result _list. = "<<a href= '/" mailto: $email/"' > $email </A>
\ n ";
}
}
}
Else
{
echo "Result set empty for query: $ldap _query";
}

Close connection
Ldap_close ($connect _id);

Custom Form
echo "<CENTER> <form action= ' \" $PHP _self\ "' method= '" get\ "'";
echo "Search in:<select name= '" server_id\ "'"; Loop to establish a select option for ($i =0; $i
echo "<option selected Value= '" $i \ "' >" $LDAP _name[$i]. " </OPTION> "; echo "</SELECT>
";
echo "Search for:<input name= '" common\ "' type= '" text\ "'";
echo "<input name= '" Lookup\ "' type= '" submit\ "' value= '" go\ "
";
echo "(You can use * for wildcard searches, ex. * Stanley'll find all Stanleys)
";
echo "</FORM> </CENTER>";

Show results
if ($result _list)
{
echo "<CENTER> <table border= ' \" 1\ "' cellpadding= '" 10\ "' cellspacing= '" 0\ "'
Bgcolor=\ "#FFFFEA \" width=\ "450\" > <TBODY> <TR> <TD> $result _list </TD> </TR>
</TBODY> </TABLE> </CENTER>;
}
Else
echo "No Results";
}

? >



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.