PHP authentication against Microsoft Active directory then returning users' group

We had the following script running a on redhat linux box w/php 4.x-apache 1.3.x authenicating a user against a NT4 domain controller which worked great until the recent upgrade to Active Directory. Not only does the script auth against the domain controller but if the user exists then this script determines which of the three groups the user is in. I have googled everywhere but not found much that is useful besides some ldap info which have posted the links to below our original script. I'm looking for a working script not a bunch of links, i'm not a pro with microsofts server stuff so a simple script that can do the same as our previous one would be great, thanks.

<?PHP
include("connect.php3");
function domainAuth($login, $pass){
            $primary_svr = "ufdc01.ad.ufl.edu";
            $domain = "UFAD";
            $group = "FRE";
            $authToNTDomain = validate($primary_svr, $domain, $group, $login, $pass);
            //echo "Class: authToNTDomain: $authToNTDomain<BR>";
            //echo smbauth_err2str($authToNTDomain) . "<BR>";
            if ($authToNTDomain == "0"  && $login != "" && $pass != "") {
                  return true;
                  //$this->authedToDomain = true;
                  //echo "this->authedToDomain = true<BR>";
            } else {
                  return false;
                  //$this->authedToDomain = false;
                  //echo "this->authedToDomain = false<BR>";
            }
}

function getGroup($login, $pass){
            $server = "ufdc01.ad.ufl.edu";
            $domain = "UFAD";
            $groups = getUserGroups($server, $domain, $login, $pass);

            //$err = err2str();
            //echo "error: $err<BR>";            
            $numItems = getNumItems($groups);
            $i = 0;
            while($i < $numItems){
                  $item = getItem($groups, $i);
                  //echo "$item<BR>";
                  $groupList[] = $item;
                  $i++;
            }
            
            $numGroups = count($groupList);
            for($g=0;$g < $numGroups;$g++){
                  //echo  "list: $groupList[$g] <BR>";
                  if ($groupList[$g] == "IF-FREDStaff"){
                        $group = "staff";
                        return $group;
                  } elseif ($groupList[$g] == "IF-FREDGrad"){
                        $group = "student";
                        return $group;
                  } elseif ($groupList[$g] == "IF-FREDFaculty"){
                        $group = "faculty";
                        return $group;
                  }
            }

            return false;

}


function inFRE($ID){
            $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            }

            if($located){
                  return true;
                  //$this->inFRE = true;
            } else {
                  return false;
                  //$this->inFRE = false;
            }
}




function hasBios($ID){
      $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $data = mysql_fetch_object($result);
                  $type = $data->type;
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  if(mysql_num_rows($result) == 1 ) {
                        $type = "Student";
                  }
            }      
                        

      if ($type == "Student"){
          $database = "student_bios";
      } elseif ($type == "Faculty"){
          $database = "faculty_bios";
      } elseif ($type == "Staff"){
          $database = "staff_bios";
      }

      $query = "SELECT bios_ID FROM $database WHERE bios_ID='$ID'";
      $result = mysql_query($query);
      $hasBios = mysql_num_rows($result);
      return $hasBios;
}


function createSession($login_user){
      global $HTTP_REFERER;
      session_id();
      session_start();
      $_SESSION["Username"] = "$login_user";
      $_SESSION["LoggedIn"] = 1;
      $sessionID = session_id();
      //SetCookie("sessionID", $sessionID);
      Header("Location: $HTTP_REFERER");
      return 1;
}


function isSupport($login, $pass){
                $server = "nt-pdc";
                $domain = "ifasdom";

                $groups = getUserGroups($server, $domain, $login, $pass);
                //$err = err2str();  
                //echo "error: $err<BR>";
                $numItems = getNumItems($groups);
                $i = 0;
                while($i < $numItems){
                        $item = getItem($groups, $i);
                        //echo "$item<BR>";
                        $groupList[] = $item;
                        $i++;
                }
                       
                $numGroups = count($groupList);
                for($g=0;$g < $numGroups;$g++){
                        //echo  "list: $groupList[$g] <BR>";
                        if ($groupList[$g] == "FREDSupport"){
                              return true;
                        //will return true and exit if found as support
                        }
                }
            // false if after looking through groupList array and not found as FREDSupport  
                return false;
}


?>

http://www.markround.com/ldap.html
http://www.developer.com/lang/php/article.php/3100951
http://www.experts-exchange.com/Web/Web_Languages/PHP/PHP_Windows/Q_21043386.html

LVL 3
adamshieldsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ryan-hCommented:
can u post any errors you are receiving? either from php/apache, the error_log file or the domain controllers event logs. and if not can u tell us what the script is 'now' doing if anything?

I don't have a domain controller handy to play with so i'll need a bit more info
0
adamshieldsAuthor Commented:
Ok, I've got users authenicating agaisnt the AD server now and it's successfully returning one of the three groups. Now I have a new problem.

Go here http://www.fred.ifas.ufl.edu/bios/createlogin.php and try to login just using the username 'rsreese' and you'll see a mysql error

Duplicate entry '' for key 1

Here is my table layout:

CREATE TABLE `staff_bios` (
  `bios_ID` varchar(33) NOT NULL default '',
  `Responsibilities` text,
  `Summary` text,
  `Current_Projects` text,
  `Web_Links` text,
  `Degrees` text,
  `Interests` text,
  `Awards_and_Achievements` text,
  `Last_Modified` int(11) default NULL,
  PRIMARY KEY  (`bios_ID`),
  UNIQUE KEY `bios_ID` (`bios_ID`)
) TYPE=MyISAM;

Should I move this over to mysql/php?


0
ryan-hCommented:
the error says u can't have duplicates in a column defined as unique.

You either need to specify the value of bios_ID in your query or set your primary key (bios_ID) to type INT and auto_increment

I'm making the assuption that bios_ID is the netbios name in which case you will need to add a new ID field and use that as the primaray key if you want an auto increment. something like this (not tested)

CREATE TABLE `staff_bios` (
  `id` int(11) NOT NULL auto_increment '',
  `bios_ID` varchar(33) NOT NULL'',
  `Responsibilities` text,
  `Summary` text,
  `Current_Projects` text,
  `Web_Links` text,
  `Degrees` text,
  `Interests` text,
  `Awards_and_Achievements` text,
  `Last_Modified` int(11) default NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `bios_ID` (`bios_ID`)
) TYPE=MyISAM;
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
adamshieldsAuthor Commented:
Ok, well I figure out what I had to do. First off you must have some type of rights to view the users group information in the AD schemea. The following is the edited script.:


<?php
error_reporting(E_ALL);
      mysql_connect("localhost","user","pass");
      mysql_select_db("database");



function domainAuth($login, $pass){      
      $ldap_host = "ad.ufl.edu";
      $base_dn = "OU=FRE,OU=IFAS,OU=People,OU=UF,DC=ad,DC=ufl,DC=edu";
      
      $domain = "@ufl.edu";
      $ldap_user = $login.$domain;
      $ldap_pass = $pass;

//      $connect = ldap_connect( $ldap_host, $ldap_port)
      $connect = ldap_connect( $ldap_host)
       or exit("Could not connect to LDAP server");

      // required to search AD, according to note in PHP manual notes
      ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
      ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);

      $bind = ldap_bind($connect, $ldap_user, $ldap_pass)
           or exit("Could not bind to $ldap_host");

      echo "Successful bind to $ldap_host with $bind<br><br>\n";
      
ldap_unbind($connect);
}



function getGroup($login){

      $ldap_host = "ad.ufl.edu";
      $base_dn = "OU=FRE,OU=IFAS,OU=People,OU=UF,DC=ad,DC=ufl,DC=edu";
      $filter = "(CN=$login)";
      $ldap_user = "user@withadmin.rights.com";
      $ldap_pass = "thepass";


$connect = ldap_connect( $ldap_host)
       or exit("Could not connect to LDAP server");

      // required to search AD, according to note in PHP manual notes
      ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
      ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);

      $bind = ldap_bind($connect, $ldap_user, $ldap_pass)
           or exit("Could not bind to $ldap_host");

      echo "Successful bind to $ldap_host with $bind<br><br>\n";

      $read = ldap_search($connect, $base_dn, $filter)
           or exit("Unable to search ldap server");

      $info = ldap_get_entries($connect, $read);
      echo $info["count"]." entries returned for $filter<br><br>\n";

      $ii=0;
      for ($i=0; $ii<$info[$i]["count"]; $ii++){
            $data = $info[$i][$ii];
            if ($data == "memberof") {
                  $total_memberof = (count($info[$i][$data]));
                  echo "Total memberof entries returned: $total_memberof<br><br>\n";
                  $total = 0;
                  $total = count($info[$i][$data]);
                  $jj=0;
                  for ($jj=0; $jj<$total; $jj++) {
                        if ($info[$i][$data][$jj] == "CN=IF-FREDStaff,OU=Groups,OU=FRE,OU=Campus,OU=-Co-Managed,OU=IFAS,OU=Departments,OU=UF,DC=ad,DC=ufl,DC=edu") {
                              //echo "<b>Got Staff Match</b> ";
                              $group = "IF-FREDStaff";
                              return $group;
                        } elseif (($info[$i][$data][$jj] == "CN=IF-FREDFaculty,OU=Groups,OU=FRE,OU=Campus,OU=-Co-Managed,OU=IFAS,OU=Departments,OU=UF,DC=ad,DC=ufl,DC=edu") && $group == "") {
                              //echo "<b>Got Faculty Match</b> ";
                              $group = "faculty";
                              return $group;
                        } elseif (($info[$i][$data][$jj] == "CN=IF-FREDGrad,OU=Groups,OU=FRE,OU=Campus,OU=-Co-Managed,OU=IFAS,OU=Departments,OU=UF,DC=ad,DC=ufl,DC=edu") && $user_type == "") {
                              //echo "<b>Got Students Match</b> ";
                              $group = "student";
                              return $group;
                        }
                  //      echo $i." ".$ii." ".$jj."
// ".$data.":&nbsp;&nbsp;".$info[$i][$data][$jj]."<br>\n";
                  }
            }
      }

      ldap_unbind($connect);
}

function inFRE($ID){
            $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  $located= mysql_num_rows($result);
                  $data = mysql_fetch_object($result);
            }

            if($located){
                  return true;
                  //$this->inFRE = true;
            } else {
                  return false;
                  //$this->inFRE = false;
            }
}




function hasBios($ID){
      $query = "SELECT * FROM directory WHERE username='$ID'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 1 ) {
                  $data = mysql_fetch_object($result);
                  $type = $data->type;
            } else {
                  $query = "SELECT * FROM students WHERE ID='$ID'";
                  $result = mysql_query($query);
                  if(mysql_num_rows($result) == 1 ) {
                        $type = "Student";
                  }
            }      
                        

      if ($type == "Student"){
          $database = "student_bios";
      } elseif ($type == "Faculty"){
          $database = "faculty_bios";
      } elseif ($type == "Staff"){
          $database = "staff_bios";
      }

      $query = "SELECT bios_ID FROM $database WHERE bios_ID='$ID'";
      $result = mysql_query($query);
      $hasBios = mysql_num_rows($result);
      return $hasBios;
}


function createSession($login_user){
      global $HTTP_REFERER;
      session_id();
      session_start();
      $_SESSION["Username"] = "$login_user";
      $_SESSION["LoggedIn"] = 1;
      $sessionID = session_id();
      //SetCookie("sessionID", $sessionID);
      Header("Location: $HTTP_REFERER");
      return 1;
}

?>
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.