Get user windows php

Можете ли вы получить имя пользователя 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:

Читайте также:  Обновить биос lenovo g505 windows 10

= 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

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.

Читайте также:  Linux ps полный вывод

Info is session-based, so single(ish) signon is possible even in Firefox.

How to check what user php is running as?

I need to detect if php is running as nobody. How do I do this?

Are there any other names for «nobody»? «apache»? Any others?

16 Answers 16

If available you can probe the current user account with posix_geteuid and then get the user name with posix_getpwuid .

If you are running in safe mode however (which is often the case when exec is disabled), then it’s unlikely that your PHP process is running under anything but the default www-data or apache account.

Kind of backward way, but without exec/system:

If you create a file, the owner will be the PHP user.

This could also likely be run with any of the temporary file functions such as tempnam() , which creates a random file in the temporary directory and returns the name of that file. If there are issues due to something like the permissions, open_basedir or safe mode that prevent writing a file, typically, the temp directory will still be allowed.

More details would be useful, but assuming it’s a linux system, and assuming php is running under apache, it will run as what ever user apache runs as.

An easy way to check ( again, assuming some unix like environment ) is to create a php file with:

which will give you the user.

For my AWS instance, I am getting apache as output when I run this script.

You can try using backticks like this:

any of these. You can type em in your ssh command line and you will see what user is listening what service.

you can also go and check this file:

and look for these lines:

to filter out envvars file data, you can use grep:

Straight from the shell you can run:

add the file info.php to the following directory — your default http/apache directory — normally /var/www/html

with the following contents

Then httpd/apache restart the go to your default html directory http://enter.server.here/info.php

would deliver the whole php pedigree!

In my setup I want to check if the current process has permission to create folders, subfolders and files before I begin a process and suggest a solution if it looks like I can’t. I wanted to run stat( ) on various things to ensure the permissions match those of the running process (I’m using php-fpm so it varies depending on the pool).
The posix based solution Mario gave above, seems perfect, however it seems the posix extension is —disabled so I couldn’t do the above and as I want to compare the results with the response from running stat() running whoami in a separate shell isn’t helpful either (I need the uid and gid not the username).

However I found a useful hint, I could stat(/proc/self) and stat(/proc/self/attr) and see the uid and gid of the file.

Hope that helps someone else

I will be glad if it helped you

Proposal

A tad late, but even though the following is a work-around, it solves the requirement as this works just fine:

Description

The code-highlighting above is not accurate, please copy & paste in your favorite editor and view as PHP code, or save and test it yourself.

As you probably know, get_current_user() returns the owner of the «current running script» — so if you did not «chown» a script on the server to the web-server-user it will most probably be «nobody», or if the developer-user exists on the same OS, it will rather display that username.

Читайте также:  Основы графического интерфейса операционной системы windows

To work around this, we create a file with the current running process. If you just require() this into the current running script, it will return the same as the parent-script as mentioned; so, we need to run it as a separate request to take effect.

Process-flow

In order to make this effective, consider running a design pattern that incorporates «runtime-mode», so when the server is in «development-mode or test-mode» then only it could run this function and save its output somewhere in an include, -or just plain text or database, or whichever.

Of course you can change some particulars of the code above as you wish to make it more dynamic, but the logic is as follows:

  • define a unique reference to limit interference with other users
  • define a local file-path for writing a temporary file
  • define a public url/path to run this file in its own process
  • write the temporary php file that outputs the script owner name
  • get the output of this script by making a request to it
  • delete the file as it is no longer needed — or leave it if you want
  • return the output of the request as return-value of the function

wp_get_current_user() WP 2.0.4

Получает данные о текущем авторизованном пользователе (объект WP_User). Устанавливает текущего пользователя, если не установлен.

ID текущего пользователя определяется функциям:

Функция начинает работать в WP с события plugins_loaded. Если вызвать её раньше, то мы получим fatal error.

Если очень нужно вызвать функцию до события plugins_loaded , то нужно предварительно подключить зависимости:

Это pluggable функция — т.е. её можно заменить из плагина. Это значит, что она будет работать (подключается) только после подключения всех плагинов, а до этого момента функция еще не определена. Поэтому нельзя вызывать эту и зависящие от неё функции прямо из кода плагина. Их нужно вызывать через хук plugins_loaded или позднее, например хук init.

Замена функции (переопределение) — в плагине можно создать функцию с таким же названием, тогда она заменит текущую функцию.

Возвращает

WP_User. Объект WP_User.

Если пользователь не авторизован, вернет пустой объект! Т.е. Нельзя проверять авторизован ли пользователь через эту функцию:

Использование

Примеры

#1. Проверим вошел ли пользователь на сайт

Проверим авторизован (залогинен) ли пользователь. Если пользователя не существует, его ID будет равен 0:

Но лучше использовать для этих целей is_user_logged_in().

#2. Получим данные текущего пользователя

Выведем на экран различные данные о текущем авторизованном пользователе:

Заметки

  • Смотрите: _wp_get_current_user()
  • Global. WP_User. $current_user Checks if the current user is set.

Список изменений

Код wp_get_current_user() wp get current user WP 5.7.1

Cвязанные функции

Из метки: Пользователи (_user)

Еще из раздела: Остальное

Вот эта функция вызывает дисплей нейм админа

А какая функция вызывает дисплей нейм зареганого пользователя в его профиль? Просто у меня профиль на вронтедне и по этому пытаюсь тут немного видоизменять некоторые вещи. Заранее спасибо.

Что-то я не понял, чем вам пример из этой функции не подходит?

Получает массив с информацией

Во-первых не получает а возвращает, во вторых не массив а объект.

В WP и так API расхлябанное, хоть вы не вносите лишний хаос.

Вы чуть ниже пункт:

Функция получает данные пользователя. А то что конкретно она возвращает это уже чисто технический вопрос.

Правильно писать вообще так: Получает данные текущего пользователя и возвращает их в виде объекта WP_User. Ну я написал как написал, строгий шаблон для сео плох и вообще утомляет.

«Получает массив с информацией» — это тоже самое что получает массив данных в виде объекта. Но, «Возвращает массив» — это уже другое. Если вы понимаете о чем я?

В общем, поправил «массив информации» на «данные» чтобы не путать никого. Спасибо за коммент

Оцените статью