PHP on Linux authenticate users with a Windows Server Active Directory

8 Aug 2018 | PHP on Linux authenticate users with a Windows Server Active Directory |

A common request when building INTRANET web applications is to have users use only one  common shared set of  login credentials. Typically in most small and medium businesses this means that logging into a Windows Server of some kind to access the network.  Windows Servers use Active Directory (AD) ,which is  basically Microsoft’s glorified LDAP server with a slew of additional features needed for  coroporate and enterprise users.  We can leverage this by using PHP’s LDAP module to perform the login check for us..

IF you’re building your application in PHP a very easy way to do this is simply to use PHPs LDAP library and then simply call with the proper functions.  Let’s detail the steps below. I’ll be doing this from a PHP 5 , Debian installation.

LDAP tends to be tied into the Windows AD Domain Name System to allow integrated quick lookups and fast resolution of queries. LDAP generally runs on port 389 and like other protocols tends to usually conform to a distinct set of rules (RFC’s).

Step 1. Get the LDAP information (LDAP Connection URL)  from your Windows Active Directory.

First we need to verify which Windows Active directory we will be authenticating against. If your in a very large corporate environment, you may need the help of an SA (System administrator) to help guide you. Basically, the first thing you need is to know is the Domain which this users is associated with.

Essetially you need to figure out with the LDAP Connection URL is , and this requires a bit more information about how the Windows Network is configured, Typically its something like ,


then you wold combine this with the URL of the Windows AD server


To query for a particular user.  If you have accesss to the Windows Server form the command line run.

C:\Users\Administrator> dsquery user -name To*
"CN=Tony Jones,CN=Users,DC=Domain,DC=local"
"CN=Tony Smith,CN=Users,DC=Domain,DC=local"

Alternatively from the  Windows server desktop try

Active directory server -> Choose the Organization Unit OU -> Right Click -> Properties -> AttributeEditor -> DistinguishedName

The above information is necessary so you can fill in the details of the PHP script below.

Step 2. Verify PHP LDAP Library installed and enabled.

You can do this by running a simple viewing the PHP info to see which  loaded modules are currently available on your server.

Create a simple PHP file on your web server , call it test.php or something like that. When you run it it will display all the information that  PHP /Apache has configured.


Run that file from your browser http://localhost/test.php  and search for an entry like LDAP (Typically midway down the page  between JSON and LIBXML ), if you see something like the screen below.

PHP info showing LDAP module is enabled.

If you do not see this enabled, then you may want to have it added to your PHP/Apache server . The simplest way if you have a typical Debian Linux access to your server’s shell is to run the command.  For other flavors of Linux  like Redhat/Centos a similar yum command should be available.

sudo apt-get install php5-ldap

or for PHP 7

sudo apt-get install php-ldap

The command should install the necessary library and restart the server, once again re-test that it’s enabled by running the above test.php and confirming the LDAP module is correctly loaded.

Step 3. Test PHP Login against Windows AD

Finally Upload this test LDAP script to your server and save it as ldap.php (or similar name) which does the follow…

  • Usig the supplied LDAP information , don’t forget to REPLACE the DOMAIN_FQDN and LDAP_SERVER define with your actual credentials
  • Takes the user supplied username and password and
  • Issues an LDAP bind  to see if that’s a valid user
  • You get back either a True or False from the AD and you can proceed from there.
ini_set('display_errors', 'On');
define('DOMAIN_FQDN', 'YOUR_DOMAIN.local'); //Replace with REAL DOMAIN FQDN
define('LDAP_SERVER', '');  //Replace with REAL LDAP SERVER Address

//Basic Login verification
if (isset($_POST['submit']))
    $user = strip_tags($_POST['username']) .'@'. DOMAIN_FQDN;
    $pass = stripslashes($_POST['password']);

    $conn = ldap_connect("ldap://". LDAP_SERVER ."/");

    if (!$conn)
        $err = 'Could not connect to LDAP server';

//        define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);  //Already defined in PHP 5.x  versions
        ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);

        $bind = @ldap_bind($conn, $user, $pass);

        ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error);

        if (!empty($extended_error))
            $errno = explode(',', $extended_error);
            $errno = $errno[2];
            $errno = explode(' ', $errno);
            $errno = $errno[2];
            $errno = intval($errno);

            if ($errno == 532)
                $err = 'Unable to login: Password expired';

        elseif ($bind)
      //determine the LDAP Path from Active Directory details
            $base_dn = array("CN=Users,DC=". join(',DC=', explode('.', DOMAIN_FQDN)), 
                "OU=Users,OU=People,DC=". join(',DC=', explode('.', DOMAIN_FQDN)));

            $result = ldap_search(array($conn,$conn), $base_dn, "(cn=*)");

            if (!count($result))
                $err = 'Result: '. ldap_error($conn);

                echo "Success";
        /* Do your post login code here */

    // session OK, redirect to home page
    if (isset($_SESSION['redir']))
        header('Location: /');

    elseif (!isset($err)) $err = 'Result: '. ldap_error($conn);

<!DOCTYPE html>
<title>PHP LDAP LOGIN</title>
<div align="center">

<div style="margin:10px 0;"></div>
<div title="Login"  id="loginbox">
    <div style="padding:10px 0 10px 60px">
    <form action="<?php echo $_SERVER['PHP_SELF'] ?>" id="login" method="post">
        <table><?php if (isset($err)) echo '<tr><td colspan="2" class="errmsg">'. $err .'</td></tr>'; ?>
                <td><input type="text" name="username" autocomplete="off"/></td>
                <td><input type="password" name="password"  autocomplete="off"/></td>
        <input class="button" type="submit" name="submit" value="Login" />

Security Considerations:

By default, LDAP traffic is transmitted unsecured; this may or may not be a concern in an Intranet setting, for maximum safety use SSL technology to encrypt the traffic. Also most Windows Server AD will LOCK the account after n unsuccessful re-tries so be aware of this when testing your PHP login script.

Hopefully this will provide an easy way to integrate your PHP scripts with your INTRANET servers, making it easier to keep manage user accounts and access from one spot.

5 (100%) 1 vote

2 thoughts on “PHP on Linux authenticate users with a Windows Server Active Directory

  1. Reply Sam Luii Aug 8,2018 2:07 pm

    How can you map this to a MySQL server? that is how can authentication be used with a mySQL table

  2. Reply Ramesh Sanjiv Aug 14,2018 2:26 pm

    How do you setup an SSL connection to make sure that the credentials are secured

Leave a Reply