PHP LDAP Connection - php

I was sent the following LDAP parameters, but am not sure how to establish a connection in PHP. I'm not sure which PHP function to use with each set of parameters. Here are the parameters I was given:
Server: ldaps://the_server.com:636
root DN: dc=the_info,dc=more_info,dc=com
User search base: ou=CompanyUsers
User search filter: sAMAccountName={0}
Group search base: OU=Security,OU=CompanyGroups
Group search filter: cn={0}
Group membership: Group membership attribute = memberOf
Display Name LDAP attribute: displayname
Email Address LDAP atribute: mail
If someone could provide a php script for me that would be great! This is my first time using LDAP and still do not understand all these parameters.

Following is the working code for linux base ldap.
It might be helpful to you.
<?php
$username = 'uid=amitkawasthi,ou=CompanyUsers,dc=the_info,dc=more_info,dc=com';
$password= 'test';
$ds=ldap_connect("the_server.com, 636");
echo $ds;
if ($ds) {
echo "Binding ...";
$r=ldap_bind($ds, $username, $password);
if ($r)
{
$sr=ldap_search($ds,"ou=CompanyUsers,dc=the_info,dc=more_info,dc=com", "uid=amitkawasthi");
$entry = ldap_first_entry($ds, $sr);
$attrs = array();
$attribute = ldap_first_attribute($ds,$entry,$identifier);
while ($attribute) {
$attrs[] = $attribute;
$attribute=ldap_next_attribute($ds,$entry,$identifier);
}
echo count($attrs) . " attributes held for this entry:<p>";
$ldapResults = ldap_get_entries($ds, $sr);
//for ($item = 0; $item < $ldapResults['count']; $item++) {
// for ($attribute = 0; $attribute < $ldapResults[$item]['count']; $attribute++) {
//echo $data = $ldapResults[$item][$attribute];
echo $data = $ldapResults[0][$attribute];
echo $data.": ".$ldapResults[0][$data][0]."<br>";
//}
///echo '<hr />';
echo "OK";
}
else
{
echo "Fail";
}
}
?>
============================

Related

PHP mysqli_query() expects parameter 1 to be mysqli, null given in Confusing help needed

I am trying to store IP's in a MySQL database and I had a few problems with it which i was able to fix but i keep getting 1 error for people that trying to get onto my website. So when someone gets on my website their IP is displayed with a time stamp but it only works when I connect to my website. When I got my friend to go onto my website he got an error saying why u no query? which helps me find out where the problem is. Now the problem is that I have been trying to solve this issue for the past 2 hours with no luck :(
Screenshot of my screen: My screen
Screenshot of my friends screen: Friends screen
<html>
<head>
<title>Your IP!</title>
</head>
<body>
<?php
$db_host = '127.0.0.1';
$db_user = '***************';
$db_pwd = '*************';
$db = '***************';
// Find their IP and tell them what it is.
$con=mysqli_connect($db_host, $db_user, $db_pwd);
if (getenv('HTTP_X_FORWARDED_FOR')) {
$pip = getenv('HTTP_X_FORWARDED_FOR');
$ip = getenv('REMOTE_ADDR');
echo "Your Proxy IP is: ".$pip."(via ".$ip.")";
} else {
$ip = getenv('REMOTE_ADDR');
echo "Your IP is: ".$ip;
}
echo "<br /><br />";
// Try to select the database.
if(!mysqli_select_db($con, $db)) {
// die("why u no use db? ".mysql_error());
die("why u no use db?");
}
// Try to perform query.
// This is a function so it may easily be called multiple times.
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
}
return $result; // Give back result.
}
// Try to see if they are in the database already,
// and if not, then add them.
$result = do_query("select ip from ips where ip='".$ip."'");
$rows = mysqli_num_rows($result);
if($rows == 0) {
do_query("insert into ips (ip) values ('".$ip."')");
}
// Now, display the table.
$result = do_query("select * from ips");
$cols = mysqli_num_fields($result);
echo "<table cellpadding=\"5\" bgcolor=\"#7F7F7F\"><tr>";
for($i = 0; $i < $cols; $i++) {
echo "<td>".mysqli_fetch_field($result)->name."</td>";
}
echo "</tr>";
while($row = mysqli_fetch_row($result)) {
echo "<tr>";
for($i = 0; $i < $cols; $i++) {
if($row[$i] == $ip) { // bold their IP.
echo "<td><b>".$row[$i]."</b></td>";
} else {
echo "<td>".$row[$i]."</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
So first I changed
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
to
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die(mysqli_error($con));
Which showed me the error which was Duplicate entry '0' for key 'PRIMARY' and the problem was that I did not set AUTO_INCREMENT on the Primary key.

Warning: ldap_search(): Search: Bad search filter

I am trying to create a login page using PHP.
Goals:
1. The user is able to sign in using the same username/password he uses when logging into Windows
2. The user will be redirected to a page depending on the group he belongs to
So the 1st goal is solved. The problem now is the 2nd goal.
I get an error when I run the script:
Warning: ldap_search(): Search: Bad search filter
Script:
$ldap['user'] = "domain\user123";
$ldap['pass'] = "password123";
$ldap['host'] = 'site.domain.com';
$ldap['port'] = 389;
$ldap['dn'] = "DC=site, DC=domain, DC=com";
$ldap_user_group = "User";
$ldap_manager_group = "Admin";
$ldap['conn'] = ldap_connect( $ldap['host'], $ldap['port'] )
or die("Could not connect to {$ldap['host']}" );
$ldap['bind'] = ldap_bind($ldap['conn'], $ldap['user'], $ldap['pass']);
if( !$ldap['bind'] )
{
echo "Login Failed";
}
else if( $ldap['bind'] )
{
$filter = "(sAMAccountName=" . $ldap['user'] . ")";
$attr = array("memberof");
$result = ldap_search($ldap['conn'],$ldap['dn'], $filter, $attr)
or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap['conn'], $result);
ldap_unbind($ldap);
foreach($entries[0]['memberof'] as $grps)
{
if (strpos($grps, $ldap_manager_group))
{
//redirect to Admin page
}
if (strpos($grps, $ldap_user_group))
{
//redirect to User page
}
}
I'm really lost as I have no idea what must be causing this error.
You get a bad search filter as you are passing in a slash into the filter. You are using $ldap['user'] = "domain\user123"; in your filter here $filter = "(sAMAccountName=" . $ldap['user'] . ")";
Depending on your AD setup, you'll probably want to use something like $filter = "(sAMAccountName=user123)";

LDAP search get user givenname by userid

I have successfully run ldap_connect and ldap_bind commands in my php script. Now I need to get guvenName by user id. How can i do this.
$username = $_POST['username'];
$password = $_POST['password'];
define('LDAP_SERVER', 'localhost');
define('LDAP_PORT', 389);
define('LDAP_TOP', 'ou=people,dc=domain,dc=com');
$ds = ldap_connect(LDAP_SERVER, LDAP_PORT);
if (!$ds) {
echo "FALSE";
}
if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
#ldap_close($ds);
echo "FALSE";
}
$dn = 'uid=' . $username . "," . LDAP_TOP;
if (!ldap_bind($ds, $dn, $password)) {
echo "FALSE";
}
In general it's quite simple
public function getusercn($accountname)
{
$filter_person = "(&(sAMAccountName={$accountname}))";
$sr_person = ldap_search($this->ds_ad,$this->base_user_dn,$filter_person);
$sr = ldap_get_entries($this->ds_ad, $sr_person);
$attr = $sr[0]["givenName"][0];
return $attr;
}
$this->ds_ad - it's $ds in your code
$this->base_user_dn - is base OU from which you want to search (like LDAP_TOP in your case)
sAMAccountName - is "user id" attribute in your case uid
givenName - is attribute what you are looking for
All of attributes are already in $sr variable, so you can use var_dump to inspect all content.

Search Multiple AD DN's withPHP

Hi I have a PHP script that searches my AD, but how can I make it search more than one DN. I've tried the exmample on php.net and cannot get it to work.
Help appreciated:
<?php echo "<?xml version='1.0' encoding='utf-8' ?>" ?><?php echo "<ul class='LSRes'>" ?>
<?php
if( isset($_GET['q']) &&!empty($_GET['q']) ){
// all your ldap code
// Designate a few variables
$host = "10.10.10.10"; // Add in your AD host name or IP
$user = "DOMAIN\user"; // Add in your AD access account user name
$pswd = "password"; // Add in your AD access account user name password
$ds = ldap_connect($host)
or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
or die ("Could not set ldap protocol");
// Binding to ldap server
$bd = ldap_bind($ds, $user, $pswd)
or die ("Could not bind");
// Create the DN - Add in the OU of your AD
$dn[] = "OU=uk,OU=Accounts,DC=mywebsite,DC=com";
$dn[] = "OU=us,OU=Accounts,DC=mywebsite,DC=com";
$id[] = $ds;
$id[] = $ds;
//$filter = 'samaccountname='.$_POST['username'];
$filter = "(|(givenName=".$_GET['q']."*) (sn=".$_GET['q']."*) (displayname=".$_GET['q']."*) (samaccountname=".$_GET['q']."*))";
$result = ldap_search($id,$dn,$filter);
$search = false;
foreach ($result as $value) {
if(ldap_count_entries($ds,$value)>0){
$search = $value;
break;
}
}
if($search){
$entries = ldap_get_entries($ds, $search);
}
if ($entries["count"] > 0) {
for ($i=0; $i<$entries["count"]; $i++) {
echo "<span class='LSstyle'>Name: <strong>".$entries[$i]["displayname"][0]." ".$entries[$i]["sn"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Short name: <strong>".$entries[$i]["samaccountname"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Phone: <strong>".$entries[$i]["telephonenumber"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Title: <strong>".$entries[$i]["title"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Dept: <strong>".$entries[$i]["department"][0]."</strong></span></p>";
}
} else {
echo "<span class='LSstyle_noresults'><strong>No results found</strong></span>";
}
ldap_unbind($ad);
}
?>
Seeing as ldap_search does not take an array as $base_dn, you will probably have to loop $dn as Viper_Sb suggested.

Trouble with PHP LDAP code to check memberOf a certain group

I am having trouble with the following code which should check to see if $user is in AlumniDBusers or AlumniDBmanagers groups in AD
The entries[0] array always returns blank
Can anyone see what might be wrong?
Thanks
// Active Directory server
define('LDAP_HOST','dc1.college.school.edu');
// Active Directory DN
define('LDAP_DN','OU=Alumni Relations,OU=Departments,DC=college,DC=school,DC=edu');
// Active Directory user group
define('LDAP_USER_GROUP','AlumniDBusers');
// Active Directory manager group
define('LDAP_MANAGER_GROUP','AlumniDBmanagers');
$ldap = ldap_connect(LDAP_HOST);
echo "LDAP CONNECTED<br />";
if($bind = ldap_bind($ldap, $user, $password)) {
echo "PASS BIND<br />";
$filter = "(samAccountName=" . $user . ")";
$attrs = array("memberOf");
$result = ldap_search($ldap, LDAP_DN, $filter, $attrs);
$entries = ldap_get_entries($ldap, $result);
echo "ENTRY RESULTS: ";
print_r($entries[0]['memberOf']);
echo "<br />";
// see if member is in user or manager group
if (in_array(LDAP_USER_GROUP,$entries[0]['memberOf']) || in_array(LDAP_MANAGER_GROUP,$entries[0]['memberOf']))
{
echo "IN GROUP";
ldap_unbind($ldap);
} else {
echo "NOT IN GROUP";
ldap_unbind($ldap);
}
} else {
echo "FAIL BIND";
ldap_unbind($ldap);
}
Got it to work, my DN was wrong
Code is right
link text
PHP manual
"When adding/editing attributes for a user, keep in mind that the 'memberof' attribute is a special case. The memberOf attribute is not an accessible attribute of the user schema."

Categories