Search code examples
phpldapldap-query

LDAP Connection with PHP Issue


I am currently trying to connect out to our Active Directory to do some fancy searching magic. I have all the fancy searches written in python, now we are just trying to port it over to PHP. I am having issue getting my connection to the ldap server working. I am not getting any error messages and my informative echo's aren't displaying, neither is my footer. Any help would be appreciated! Thanks!

Here is the code:

<?php
    include "src/header.php";
    echo "Well Hello-01<br>";

    if(isset($_POST['username'])){
        $User = 'AD\\' . $_POST['username'];
    }
    if(isset($_POST['password'])){
        $Pass = $_POST['password'];
    }



    echo "Username: " . $User . "<br>";
    echo "Password: " . $Pass . "<br>";

    $ldapconn = ldap_connect("ldap://ad.whatever.com")
         or die("Could not connect to LDAP server");

    if($ldapconn){  
        echo "Attempting Bind";
        //binding to ldap 
        $ldapbind = ldap_bind($ldapconn, $User, $Pass);

        //Verify Bind
        if($ldapbind){
            echo "LDAP bind successfull...";
        }else{
            echo "LDAP bind failed...";
        }
    }else{
        echo "Fail";
    }

    include "src/footer.php";
?>

</body>`

And for whatever it's worth here is what is output to the screen: Screenshot


Solution

  • I made this code a little while ago, maybe it can help you:

    <?php
        $username = $_POST['USERNAME'];
        $password = $_POST['USERPASS'];
        $server = 'AD_SERVER_IP_GOES_HERE';
        $domain = '@MY_DOMAIN.COM'; 
        $port = 389; //default connection port
        $dn = "DC=MY_DOMAIN,DC=COM";
        $filter = "(&(samaccountname=".$username."))";
        $params = array("sn","givenName","samAccountName",
                         "mail","displayName","department",
                         "title","company","streetAddress",
                         "department","memberOf");
    
        /*these are parameters you want to retrieve from a given user*/
    
    
        $connection = ldap_connect($server, $port);
            if (!$connection) {
            echo 'no_server';
    
        }
    
    
        $bind = @ldap_bind($connection, $username.$domain, $password);
        if (!$bind) {
            echo 'user_error';
        }
        else
        {
            $query_user = ldap_get_entries($connection,ldap_search($connection,$dn,$filter,$params));
    
            print_r($query_user);
        }
    
        // Close conection
    
        ldap_close($connection);
    
    }
    

    ?>