ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Use Windows Login in PHP Applications

Updated on January 17, 2014

As a developer you may run into a situation such as what I have, numerous applications deployed and or created and deployed.

With multiple logins for all the apps, we had to find way to integrate all logins for better management and maintenance.

Since we were using Apache with a PHP server, the solution was to find a way to consolidate the logins usin PHP.

The answer is ldap() (Lightweight Directory Access Protocol). This built in function through PHP, allows you to create username and password schemes using existing Windows authentication.

Take this snippet:

$ldaprdn = 'myName@timbuckTwo.com'; // ldap rdn or dn
$ldappass = 'password'; // associated password

// connect to ldap server
$ldapconn = ldap_connect("Ip address or domain name")or die("Could not connect to LDAP server.");

That is all it takes to connect to your windows login using PHP.

Now, for the practical example:

$ldaprdn = $_POST['username']; // ldap rdn or dn
$ldappass = $_POST['password']; // associated password

// connect to ldap server
$ldapconn = ldap_connect("Ip address or domain name")or die("Could not connect to LDAP server.");

The values can be passed on using a web form with the text field names of username and password:

See form code below:

<form name="form1" method="post" action="">
<table>
<tr>
<th colspan="2"><div align="center"><?=$errorMess;?></div></th>
</tr>
<tr>
<td width="76">Username</td>
<td width="324"><input class="<?=$aClass;?>" type="text" name="username" id="username" value="<?=$_POST['username'];?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input class="<?=$aClass;?>" type="password" name="password" id="password" value="<?=$_POST['password'];?>"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="Submit" id="Submit" value="Submit"></td>
</tr>
</table>
</form>

Using the multi-purpose pages described in my other tutorial about forms, you can see how the logic before we push Submit and after we push Submit.

After pushing Submit this snippet runs:

// using ldap bind
$ldaprdn = $_POST['username']; // ldap rdn or dn
$ldappass = $_POST['password']; // associated password


//lets concatenate the proper username:

$ldaprdn = $_POST['username'] . "@whatever the domain name is";

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

if ($ldapconn) {

// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}

}

We concatenated or connected the username and the domain extension to create the proper credentials to pass on to Active Directory.

Now using this knowledge, you can create authentication using the built in Windows login, no creating usernames and passwords, Windows can manage that, leaving you to script and create.

Recap:

We went over basic authentication using a small script and how you can incorporate such a script in a real life scenario.

I invite you to look at the ldap() function and its companions, it does a lot more than what we went over, you can search, create and delete, and modify users listed on Active Directory using the function.

I will be listing other real world scenarios in the articles to come, please come and do bookmark me.

Thank you!

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Peters 

      6 years ago

      Thank you Alpho011, The script was helpful but I have a challenge. I want to create session for the user login after the user has successfully login wt the AD username and password.

      For example: $_SESSION['email'] = $data["mail"][0];

      $_SESSION['fullname'] = $data["cn"][0];

      $_SESSION['employee_id'] = $data["userprincipalname"][0];

      $_SESSION['last_name'] = $data["sn"][0];

      but this is not working. Please your help will be appreciated

      Thank you in anticipation.

    • profile image

      kubik256 

      6 years ago

      There is tested function I wrote for checking users on Windows 2003 server LDAP.

      Just pass these params:

      $un = user name

      $pwd = password

      $srv = LDAP server

      $cp = LDAP port (usualy 389)

      $dn = full domain name (...after @)

      It returns TRUE if user check was successful or FALSE if it fails. (FALSE = bad login or error in LDAP connection, becouse I don't need distinguish that...)

      -------------------------------------------------------

      function login_check($un,$pwd,$srv,$cp,$dn){

      $ds=ldap_connect($srv, $cp);

      ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);

      ldap_set_option($ds,LDAP_OPT_REFERRALS,0);

      $r=ldap_bind($ds,$un.'@'.$dn,$pwd);

      ldap_unbind($ds);

      ldap_close($ds);

      return ($ds && $r);

      }

      -------------------------------------------------------

      Hope, somebody could use this ;) BR

    • profile image

      kubik256 

      6 years ago

      Nice, taht's exactly what I was looking for ;)

      Many many thanx, BR.

    • profile image

      Heena 

      6 years ago

      Hi Georgia,

      I want to connect window machine from PHP. Let me tell you what exactly i want to do is i want to run some program by passing data from web app based on php. and retrieve result from that program and display on web page. I have to use windows machine as that program is supporting only windows.

      Many many thanks, I hope to get some idea.

    • profile image

      SarahB722 

      6 years ago

      Thank you so very much I have been trying to make this work for a week now and this was SO helpful!!

    • profile image

      george_ro 

      7 years ago

      is is posible to read the username and password from windows log in and use this to authenticate against AD ?

    • snkhan120 profile image

      snkhan120 

      8 years ago

      very nice article about php

    • profile image

      benedictine191 

      8 years ago

      may i ask hub?

      i was build a website using PHP and active directory..

      what i want to ask,

      could you fixed my code..because i am newbie and wanna try it..

      this is my form code

      Nama

      Password

      and this is my connection code (PS : my domain name's is ABC.com and i have OU name's abc and the password aaa)

      $ldaprdn = 'abc@CTO.com'; // ldap rdn or dn

      $ldappass = 'aaa'; // associated password

      // connect to ldap server

      $ldapconn = ldap_connect("LDAP.CTO.com")or die("Could not connect to LDAP server.");

      and this is my dologin.php code

      $ldaprdn = $_POST['username']; // ldap rdn or dn

      $ldappass = $_POST['password']; // associated password

      //lets concatenate the proper username:

      $ldaprdn = $_POST['username'] . "@CTO.com";

      // connect to ldap server

      $ldapconn = ldap_connect("ldap.CTO.com")

      or die("Could not connect to LDAP server.");

      if ($ldapconn) {

      // binding to ldap server

      $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

      // verify binding

      if ($ldapbind) {

      echo "LDAP bind successful...";

      } else {

      echo "LDAP bind failed...";

      }

      }

      i still confused where's the error..

      and one..if i wanna connect this php to active directory?

      could i install php in windows server first?

      or i can cross it with windows xp to windows server?

      (PS: my php file was in windows xp)

      thanks before

    • profile image

      Felix 

      8 years ago

      may i ask hub?

      i was build a website using PHP and active directory..

      what i want to ask,

      could you fixed my code..because i am newbie and wanna try it..

      this is my form code

      Nama

      Password

      and this is my connection code (PS : my domain name's is ABC.com and i have OU name's abc and the password aaa)

      and this is my dologin.php code

      i still confused where's the error..

      and one..if i wanna connect this php to active directory?

      could i install php in windows server first?

      or i can cross it with windows xp to windows server?

      (PS: my php file was in windows xp)

      thanks before

    • profile image

      osama 

      9 years ago

      Thank you wonderful information

      http://www.moshreq.com/forum

    • profile image

      amrozaki 

      9 years ago

      this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put acopy of this lesson on my site here www.7asryat.prnamg.net

    • profile image

      sdsds 

      9 years ago

      &lt;!-- /* Font Definitions */ @font-face {font-family:"Microsoft Sans Serif"; panose-1:2 11 6 4 2 2 2 2 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:1627421663 -2147483648 8 0 66047 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:right; mso-pagination:widow-orphan; direction:rtl; unicode-bidi:embed; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} @page Section1 {size:612.0pt 792.0pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:36.0pt; mso-footer-margin:36.0pt; mso-paper-source:0;} div.Section1 {page:Section1;} --&gt; this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a copy of this lesson on my site here

    • profile image

      sayed 

      9 years ago

      this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a copy of this lesson on my site here

      www.alhmaya.com

      www.ay300.com

    • Alpho011 profile imageAUTHOR

      Alpho011 

      9 years ago from Marietta, Georgia

      Just wanted to thank you all for reading and hopefully getting something out of these how tos, once again, thanks.

    • profile image

      dolo 

      9 years ago

      good

    • profile image

      al3boshi 

      9 years ago

      his is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a copy of this lesson on my site here

      http://www.al3boshi.com/vb

    • profile image

      doross 

      9 years ago

      this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a copy of this lesson on my site herewww.doross.org

    • INDRANI profile image

      INDRANI 

      9 years ago from INDIA

      Thanks for sharing your excellent information.Very informative.

    • profile image

      Jim Gaudet 

      9 years ago

      Nice, now we mix the open source apps into the local Intranet..Thanks

      :)

    • Alpho011 profile imageAUTHOR

      Alpho011 

      9 years ago from Marietta, Georgia

      Thank you ZeeaD

    • profile image

      ZeeaD 

      9 years ago

      this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a copy of this lesson on my site herewww.7wass.com

    • Alpho011 profile imageAUTHOR

      Alpho011 

      9 years ago from Marietta, Georgia

      Thank you Lgali, I hope that what I write can benefit anyone who chooses to use it.

      Thank you

    • Lgali profile image

      Lgali 

      9 years ago

      another good hub

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)