PHP通过LDAP获取Windows登录用户的samaccountname/UPN咨询
Answer to Your LDAP/AD Username Question
Hey there! Let's break this down clearly so you can pick the right attribute for your PHP LDAP setup.
First: What's the Difference Between samaccountname and userprincipalname?
These are both unique identifiers for AD users, but they serve different purposes:
samaccountname: This is the classic Windows short username (e.g.,jdoe). It's the part users enter when logging in with theDOMAIN\usernameformat, tied to NTLM authentication. Every AD user must have this attribute—it’s limited to 20 characters and unique within the domain.userprincipalname(UPN): This uses an email-like format (e.g.,john.doe@yourdomain.com). It’s designed for Kerberos authentication, works seamlessly across trusted domains, and supports longer character lengths. While most AD environments set this for users, it’s technically optional (though rare to leave blank).
Which One Should You Choose?
It depends on your use case:
- If your app integrates with traditional Windows systems, or users log in using the
DOMAIN\usernamepattern, go withsamaccountname—it’s reliable and universally supported for local domain logins. - If you’re using modern authentication (Kerberos), want users to log in with an email-like identifier, or have cross-domain needs,
userprincipalnameis the better fit.
Tweaking Your Existing Code
Your current code already includes samaccountname in the attributes array—great start! If you want to test both attributes to see what your AD returns, just add userprincipalname to the list:
$ldap_bind = ldap_bind($ldap_con, $username, $ldap_password); if ($ldap_bind) { // Add userprincipalname to view both attribute values $attributes = array("displayname", "mail", "samaccountname", "userprincipalname"); // Note: Your current filter (CN=*) returns all objects—if targeting a specific group, use a filter like: // $filter = "(&(objectClass=user)(memberOf=CN=YourTargetGroup,OU=Groups,DC=yourdomain,DC=com))"; $filter = "(CN=*)"; $result = ldap_search($ldap_con, $ldap_dn, $filter, $attributes); $entries = ldap_get_entries($ldap_con, $result); var_dump($entries); } var_dump($ldap_bind);
Running this will show you exactly what values your AD stores for each attribute, which can help confirm your choice.
内容的提问来源于stack exchange,提问作者AntonyMN
相关产品推荐
相关产品推荐

