Sample Active Directory command line php script

Here is a sample Active Directory php script that you can user for debugging and testing your configuration

Login in your host, save the php script below, give it a name, e.g. "ad_test.php" and change the following variables at the beginning to match your configuration:

$basedn = "DC=domain,DC=company,DC=com";
$ldapuser = '';
$ldappass = "yoursupersecretpass";
$ldapserver = "";
$ldapport = 389; // 389 is the default port number for AD servers
$uid = "username"; // uid to search for

Then run the script:
user@host:~/tests$ php ad_test.php

The sample php script to test AD connectivity and attribute searching: ad_test.php


$basedn = "DC=domain,DC=company,DC=com";
$ldapuser = '';
$ldappass = "yoursupersecretpass";
$ldapserver = "";
$ldapport = 389;
$uid = "username"; // uid to search for

$LDAPFieldsToFind = array("cn", "mail", "samaccountname");

// connect to ldap server
$ldapconn = ldap_connect($ldapserver, $ldapport);

// Setting ldap connection options 
if (ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  print "AD version 3\n";
} else {
  print "AD version 2\n";
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);

// binding to ldap server
print "Trying to bind to Server: $ldapserver with username: $ldapuser...\n";
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass);
if ($ldapbind) {
	print "\nBind succesfull\n\nSearching...\n\n";
	$userdetails = ldap_search($ldapconn, $basedn, $filter, $LDAPFieldsToFind);
	$info = ldap_get_entries($ldapconn, $userdetails);

	for ($x=0; $x<$info["count"]; $x++) {
		print "Active Directory attributes using filter $filter:\n";
		print "CN is: $nam \n";
		print "Mail is: $email\n";
		print "Uid: $samaccountname";
	if ($x==0) {
		// if nothing found 
		print "Oops, nothing was found\n";
} else {
	print "\nUnable to bind to server: Error: ".ldap_error($ldapconn) . "\n";



  1. Windows Server 2012 Active Directory, Test both on joomla 2.5.18 and joomla 3.2.2
    I got the result as the following:

    AD version 3 Trying to bind to Server: with username: intranet@vns.local... Bind succesfull Searching... Oops, nothing was found

    Please help.

  2. For $uid try both: "intranet@vns.local" and just "intranet"

  3. Hi Michael,

    I try both but no luck. If I add a new user with the same account in Active Directory (AD) then I can login with both user password and AD password.


    1. Use extra debugging to see exactly what is going on:
      Try this:

  4. Hi Michael,

    I used this script and get the message:

    Trying to bind with intranet@vns.local - mypassword


  5. This comment has been removed by the author.

  6. This piece is quite valuable for someone like myself who is new to web design development. I hope to see more of these hacks in the future.