- Можете ли вы получить имя пользователя Windows (AD) в PHP?
- Решение
- Другие решения
- get_current_user
- Описание
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 7 notes
- NTLM Authentication — Get Windows login, domain and host in PHP
- PHP get domain name [duplicate]
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged php domain-name or ask your own question.
- Linked
- Related
- Hot Network Questions
- Can you get a Windows (AD) username in PHP?
- 16 Answers 16
Можете ли вы получить имя пользователя Windows (AD) в PHP?
У меня есть веб-приложение PHP в интрасети, которое может извлечь IP и имя хоста текущего пользователя на этой странице, но мне было интересно, есть ли способ получить / извлечь их имя Active Directory / Windows, а также. Это возможно?
Решение
Проверить AUTH_USER переменная запроса. Оно будет пустым, если ваше веб-приложение разрешает анонимный доступ, но если на вашем сервере используется базовая аутентификация или встроенная проверка подлинности Windows, оно будет содержать имя пользователя, прошедшего проверку подлинности.
В домене Active Directory, если на ваших клиентах запущен Internet Explorer и разрешения вашего веб-сервера / файловой системы настроены правильно, IE автоматически отправит свои учетные данные домена на ваш сервер и AUTH_USER будет MYDOMAIN\user.name без необходимости пользователям явно входить в ваше веб-приложение.
Другие решения
У меня есть PHP MySQL работает на IIS — я могу использовать $_SERVER[«AUTH_USER»] если Я включаю проверку подлинности Windows в IIS -> Проверка подлинности и отключаю анонимную проверку подлинности (важно)
Я использовал это, чтобы получить мой пользователь и домен:
$user вернет значение как: DOMAIN\username в нашей сети, а затем это просто случай удаления DOMAIN\ из строки.
До сих пор это работало в IE, FF, Chrome, Safari (протестировано).
Посмотрите на функции библиотеки PHP LDAP: http://us.php.net/ldap .
Active Directory [в основном] соответствует стандарту LDAP.
Если вы используете Apache в Windows, вы можете установить mod_auth_sspi из
Инструкции находятся в файле INSTALL, и есть пример whoami.php. (Это просто случай копирования файла mod_auth_sspi.so в папку и добавления строки в httpd.conf.)
После установки и установки необходимых настроек в httpd.conf для защиты каталогов, которые вы хотите, PHP заполнит $_SERVER[‘REMOTE_USER’] с пользователем и доменом (‘USER \ DOMAIN’) аутентифицированного пользователя в IE — или запросите и аутентифицируйтесь в Firefox перед его передачей.
Информация основана на сеансах, поэтому единый вход (ish) возможен даже в Firefox …
Вы могли бы, вероятно, аутентифицировать пользователь в Apache с mod_auth_kerb требуя аутентифицированный доступ к некоторым файлам … Я думаю, что таким образом, имя пользователя также должно быть доступно в переменных среды PHP где-то … вероятно, лучше проверить с как только вы получите это работает.
Нет. Но то, что вы можете сделать, это разрешить администратору Active Directory включить LDAP, чтобы пользователи могли поддерживать один набор учетных данных.
Проверьте исправленный модуль аутентификации NTLM для Apache
https://github.com/rsim/mod_ntlm
Основан на модуле аутентификации NTLM для Apache / Unix
http://modntlm.sourceforge.net/
Если вы ищете для получения IDSID / имени пользователя удаленного пользователя, используйте:
Вы получите что-то вроде
iamuser1-mys.corp.company.com
Отфильтруйте оставшуюся часть домена, и вы сможете получить только IDID.
get_current_user
(PHP 4, PHP 5, PHP 7, PHP 8)
get_current_user — Получает имя владельца текущего скрипта PHP
Описание
Возвращает имя владельца текущего PHP-скрипта.
Возвращаемые значения
Возвращает имя пользователя в виде строки.
Примеры
Пример #1 Пример использования get_current_user()
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
- getmyuid() — Получение UID владельца скрипта PHP
- getmygid() — Получить GID владельца скрипта PHP
- getmypid() — Получение ID процесса PHP
- getmyinode() — Получает значение inode текущего скрипта
- getlastmod() — Получает время последней модификации страницы
User Contributed Notes 7 notes
to get the username of the process owner (rather than the file owner), you can use:
= posix_getpwuid ( posix_geteuid ());
print $processUser [ ‘name’ ];
?>
On Centos, the Red Hat linux clone, this instruction gives the file’s OWNER (the first parameter in instruction ‘chown’). It does not reveal the file’s GROUP.
get_current_user() does NOT reveal the current process’ user’s identity.
See: posix_getuid() — Return the real user ID of the current process
The information returned by get_current_user() seems to depend on the platform.
Using PHP 5.1.1 running as CGI with IIS 5.0 on Windows NT, get_current_user() returns the owner of the process running the script, *not* the owner of the script itself.
It’s easy to test — create a file containing:
echo get_current_user ();
?>
Then access it through the browser. I get: IUSR_MACHINE, the Internet Guest Account on Windows, which is certainly not the owner of the script.
Further testing of behaviour on Windows vs Linux.
On Linux this function is indeed returning the owner of the script. If you want to know the username PHP is running as you can use POSIX functions (or shell_exec with ‘whoami’).
On Windows this function is returning the username PHP is running as. Both for IIS (IUSR) and Apache (SYSTEM — which comes from the fact Apache is a service on Windows).
The behaviour on Windows is actually useful given that POSIX functions aren’t available. If you need to find the owner of the script on Windows perhaps the best way is to shell_exec to use dir /Q, and parse that.
Since this only returns the file owner and not the actual user running the script, an alternative in Linux is:
= trim ( shell_exec ( ‘whoami’ ));
?>
bobevans/somescript.php will return bobevans when calling get_current_user().
If you want to get the name of the user who executes the current PHP script, you can use
NTLM Authentication — Get Windows login, domain and host in PHP
I am working on a Single Sign-On (SSO) PHP application.
Users log in their Windows session, and they want to be automatically logged in the application with their Windows account (connected with LDAP Active Directory).
I tried this script :
This script is working on this configuration :
- Windows server 2003
- Apache 2.2 with module mod_auth_sspi
But now I need to implement this on this configuration and it does not work :
- Windows server 2008
- Apache 2.4.6 with module mod_authnz_sspi
I keep getting «NTLM Flag error!», because of this condition :
because ord($chained64[13]) returns 130, but I can not go in this condition :
Because ord($chained64<8>) always returns 1.
I tried executing the ‘whoami’ command in php, like this : echo exec(‘whoami’); -> when I execute this command in cmd.exe, I get the current logged user, but when I execute it in PHP, I get nt_authority/system.
I supposed that when PHP executes the ‘whoami’ command, Windows checks the login of Apache service. I went into Apache properties, in the ‘Log On’ tab, to log on as a valid user of the Active Directory. But then, when PHP executes echo exec(‘whoami’); , I only get the login used for Apache, and not the current user.
I am using Internet Explorer 8 to execute the PHP script.
I have this in my Apache httpd.conf ( _PATH_ is the path to my php files, maybe this is wrong ?) :
Options None AllowOverride All Order allow,deny Allow from all AuthName «SSPI Protected Place» AuthType SSPI SSPIAuth On SSPIAuthoritative On SSPIOfferBasic On SSPIOmitDomain On Require valid-user
I am logged as a domain user on the machine
When I try with Firefox, I get a prompt for a login and a password. When I post the prompt, the script gets the login from the prompt, but this is not what I want to do : I have to get this to work with IE, and I don’t want to type again login and password. I want the login of the current Windows session.
In Firefox, I went into about:config to set network.automatic-ntlm-auth.trusted-uris to my domain, thanks to @ThaDafinser. Now I do not get a prompt anymore in Firefox and everything works, but I always need to make it work on IE.
In IE, I set Local Intranet Security to the lowest, but nothing changed.
In IE, «Automatic logon with current user name and password» is checked for Local Intranet & Trusted Sites.
When I force IE to ask credentials in a prompt, if I post the prompt, IE does not return the credentials, contrary to Firefox.
I added the URL to trusted sites in IE, nothing changed.
I set security to low for trusted sites, nothing changed.
I unchecked «Use HTTP 1.1 through proxy connections» in IE > Internet Options > Advanced, I still can not have session informations on Internet Explorer, even if I use the prompt.
I added the full URL in Internet Explorer > Internet Options > Security > Local Intranet > Sites > Advanced
In Internet Explorer > Internet Options > Security > Local Intranet > Sites > Advanced, I also added the same part of the domain (mycompany.com) than I have added in Firefox to make it work, but this did not help.
Changed my httpd.conf to be compatible with Apache 2.4, according to what @timclutton said in his answer :
I tried to set a basic authentication intead of SSPI and it does not work.
AuthType Basic AuthName «Authentication Required» AuthUserFile «E:/PATH/.htpasswd» Require valid-user
PHP get domain name [duplicate]
I want to get the domain name for where the script is running. How can that be done with PHP? I see that $_SERVER[‘HTTP_HOST’] as well as $_SERVER[‘SERVER_NAME’] contain this information. Will that variable always work and should I use one over the other?
2 Answers 2
Similar question has been asked in stackoverflow before.
Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:
- no DNS support
- misconfigured
- behind load balancing software
To answer your question, these should work as long as:
- Your HTTP server passes these values along to PHP (I don’t know any that don’t)
- You’re not accessing the script via command line (CLI)
But, if I remember correctly, these values can be faked to an extent, so it’s best not to rely on them.
My personal preference is to set the domain name as an environment variable in the apache2 virtual host:
This, however, isn’t applicable in all circumstances.
Not the answer you’re looking for? Browse other questions tagged php domain-name or ask your own question.
Linked
Related
Hot Network Questions
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Can you get a Windows (AD) username in PHP?
I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?
16 Answers 16
Check the AUTH_USER request variable. This will be empty if your web app allows anonymous access, but if your server’s using basic or Windows integrated authentication, it will contain the username of the authenticated user.
In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and AUTH_USER will be MYDOMAIN\user.name without the users having to explicitly log in to your web app.
I’ve got php mysql running on IIS — I can use $_SERVER[«AUTH_USER»] if I turn on Windows Authentication in IIS -> Authentication and turn off Anonymous authentication (important)
I’ve used this to get my user and domain:
$user will return a value like: DOMAIN\username on our network, and then it’s just a case of removing the DOMAIN\ from the string.
This has worked in IE, FF, Chrome, Safari (tested) so far.
Look at the PHP LDAP library functions: http://us.php.net/ldap.
Active Directory [mostly] conforms to the LDAP standard.
We have multiple domains in our environment so I use preg_replace with regex to get just the username without DOMAIN\ .
If you’re using Apache on Windows, you can install the mod_auth_sspi from
Instructions are in the INSTALL file, and there is a whoami.php example. (It’s just a case of copying the mod_auth_sspi.so file into a folder and adding a line into httpd.conf.)
Once it’s installed and the necessary settings are made in httpd.conf to protect the directories you wish, PHP will populate the $_SERVER[‘REMOTE_USER’] with the user and domain (‘USER\DOMAIN’) of the authenticated user in IE — or prompt and authenticate in Firefox before passing it in.
Info is session-based, so single(ish) signon is possible even in Firefox.