This article shows how to configure the Apache webserver and a PHP website to optionally use NTLM authentication (Integrated Windows Authentication) to authenticate the website’s users. That means, a user may log in via his or her Windows account but does not have to. If he cannot be logged on (automatically), he just gets shown the basic website without the content for only logged on users.
First of all, you need to configure your Apache webserver to use NTLM authentication against your Windows domain. I followed this step-by-step guide to make it work: Using the NTLM part of Samba for Apache on Linux.
Then you need to configure the webserver so that access to the file auth.php is restricted to authenticated Windows users:
# require the user to login via his Windows account when accessing auth.php
AuthName "NTLM Authentication"
NTLMAuthHelper "/usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp"
# if the user cannot be authenticated he gets redirected to the main page
ErrorDocument 401 /index.php
If the user gets authenticated, auth.php stores the Windows username in the user’s session like this:
// NTLM sets REMOTE_USER to the current Windows username automatically
$_SESSION['username'] = $_SERVER['REMOTE_USER'];
Now, if the user opens the main page of the website (index.php) for the first time he needs to be redirected to auth.php to authenticate. If the authentication fails, he gets re-redirected to index.php (via ErrorDocument 401 index.php in the Apache config) and is not logged on but may browse the content of the site that is visible to everybody. But if he got authenticated correctly he is now able to see the complete content of the website.
$username = "";
$user_is_logged_in = false;
// when the user visits the site for the first time
// he has not yet been authenticated and his session is empty
// initialize the username so the user does not get
// redirected over and over again
$_SESSION['username'] = "";
$username = trim($_SESSION['username']);
// if the user got authenticated, auth.php stored the
// username in the session
if ($username != "")
$user_is_logged_in = true;
echo 'not logged in<br/>';
echo '<a href="auth.php">login</a><br/>';
echo 'logged in as: ' . $username . '<br/>';
echo 'content only visible for logged in users<br/>';
echo 'content visible for all users<br/>';