get_current_user
Результатом выполнения данного примера будет что-то подобное:
Текущий владелец скрипта: SYSTEM
Смотрите также
- 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:
$processUser = 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:
$current_user = trim ( shell_exec ( ‘whoami’ ));
?>
If you want to get the name of the user who executes the current PHP script, you can use
$username = getenv ( ‘USERNAME’ ) ?: getenv ( ‘USER’ );
echo $username ; // e.g. root or www-data
?>
If you have userdir enabled, get_current_user() returns the username of the user hosting the public_html. For example, http://example.com/~bobevans/somescript.php will return bobevans when calling get_current_user().
- Опции PHP/информационные функции
- assert_options
- assert
- cli_get_process_title
- cli_set_process_title
- dl
- extension_loaded
- gc_collect_cycles
- gc_disable
- gc_enable
- gc_enabled
- gc_mem_caches
- gc_status
- get_cfg_var
- get_current_user
- get_defined_constants
- get_extension_funcs
- get_include_path
- get_included_files
- get_loaded_extensions
- get_required_files
- get_resources
- getenv
- getlastmod
- getmygid
- getmyinode
- getmypid
- getmyuid
- getopt
- getrusage
- ini_alter
- ini_get_all
- ini_get
- ini_parse_quantity
- ini_restore
- ini_set
- memory_get_peak_usage
- memory_get_usage
- memory_reset_peak_usage
- php_ini_loaded_file
- php_ini_scanned_files
- php_sapi_name
- php_uname
- phpcredits
- phpinfo
- phpversion
- putenv
- set_include_path
- set_time_limit
- sys_get_temp_dir
- version_compare
- zend_thread_id
- zend_version
- get_magic_quotes_gpc
- get_magic_quotes_runtime
- restore_include_path
Как вывести имя авторизованного пользователя?
Только Вы бы почитали про sql-инъекции, а то так пихать в запрос все что не попадя — все равно что тянуть все в рот, что на дороге нашел.
на счет $user[‘name’]; не понятно. у меня он нигде не хранится, я вам скинул весь код.
как его записать можно?BadassRolf: вместо name — любое имя поля которое хотите чтобы выводилось в качестве имени, наверно тогда $user[«login»], если более подходящего нет ничего:)
Ну так правильно! Причем тут кнопка. Поле называется login!
измените на это:
if (isset($_POST[‘login’]))Exploding: на странице с формой находится экшн. при вводе логина и пароля проверяется событие на нажие кнопки у которой имя login_u. после этого идет сверение и устанавливается сессия.
если поставить как вы сказали, тогда не работаетBadassRolf: И хотя бы привести пример ошибки, которую выдает интерпретатор, а не просто «не работает».
Контроль ошибок включается: error_reporting(-1);Уффф. вот так 100% должно работать.
[«login»]=> string(5) — это по вашему что означает)))))
[«login_u»]=> string(0) — и вот это))if (isset($_POST['login'])) < $login_true = mysqli_query($connections, "SELECT * FROM `users` WHERE login='".$_POST['login']."' AND password = MD5('".$_POST['password']."')"); if ($login_true) < $user = mysql_fetch_assoc($login_true); $_SESSION['login_user'] = $login_true; $_SESSION['user_name'] = $user['name']; //или где там имя храниться >else echo "Не правильно"; > echo "Здрасте, ".$_SESSION["user_name"];
if (isset($_POST['login_u'])) < $login_true = mysqli_query($connections, " SELECT * FROM `users` WHERE login='".$_POST['login']."' AND password = MD5('".$_POST['password']."'); "); if ($login_true) < $count = mysqli_num_rows($login_true); if ($count >0) < $_SESSION['login_user'] = $login_true; >else < echo "Не правильно"; >> $_SESSION['user_name'] = $_POST['login']; >
BadassRolf: Ну. скрипя и отворачивая голову, учитывая что это на локалке для себя. )))
Только определение $_SESSION[‘user_name’] = $_POST[‘login’]; хотя бы в блок с проверкой запихните, а то мало ли какой пост_логин прийдет.if (isset($_POST[‘login_u’])) $login_true = mysqli_query($connections, »
SELECT * FROM `users` WHERE login='».$_POST[‘login’].»‘ AND password = MD5(‘».$_POST[‘password’].»‘);
«);
if ($login_true) $count = mysqli_num_rows($login_true);
if ($count > 0) $_SESSION[‘login_user’] = $login_true;
$_SESSION[‘user_name’] = $_POST[‘login’];
>else echo «Не правильно»;
>
>Exploding: я от силы php изучаю неделю. практикуюсь второй день) вот все и криво и как попало. с повышением знаний буду исправлять код)
Но я бы разобрался! Т.к. фактически вы вроде бы и сверились с БД но как-то хреново сверились))) Почему логин не из записи БД берется а из поста?)))) Фен-шуй за это покарает колючей плетью))
BadassRolf: Обязательно исправьте, т.к. этот вариант крайне не подходящий для постоянной работы. Заглушка, так можно сказать про него:)
get_current_user
Результатом выполнения данного примера будет что-то подобное:
Текущий владелец скрипта: SYSTEM
Смотрите также
- 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:
$processUser = 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:
$current_user = trim ( shell_exec ( ‘whoami’ ));
?>If you want to get the name of the user who executes the current PHP script, you can use
$username = getenv ( ‘USERNAME’ ) ?: getenv ( ‘USER’ );
echo $username ; // e.g. root or www-data
?>If you have userdir enabled, get_current_user() returns the username of the user hosting the public_html. For example, http://example.com/~bobevans/somescript.php will return bobevans when calling get_current_user().
- Опции PHP/информационные функции
- assert_options
- assert
- cli_get_process_title
- cli_set_process_title
- dl
- extension_loaded
- gc_collect_cycles
- gc_disable
- gc_enable
- gc_enabled
- gc_mem_caches
- gc_status
- get_cfg_var
- get_current_user
- get_defined_constants
- get_extension_funcs
- get_include_path
- get_included_files
- get_loaded_extensions
- get_required_files
- get_resources
- getenv
- getlastmod
- getmygid
- getmyinode
- getmypid
- getmyuid
- getopt
- getrusage
- ini_alter
- ini_get_all
- ini_get
- ini_parse_quantity
- ini_restore
- ini_set
- memory_get_peak_usage
- memory_get_usage
- memory_reset_peak_usage
- php_ini_loaded_file
- php_ini_scanned_files
- php_sapi_name
- php_uname
- phpcredits
- phpinfo
- phpversion
- putenv
- set_include_path
- set_time_limit
- sys_get_temp_dir
- version_compare
- zend_thread_id
- zend_version
- get_magic_quotes_gpc
- get_magic_quotes_runtime
- restore_include_path
Форум PHP программистов ► PHP практикум ► PHP для начинающих
Профиль
Группа: Пользователь
Сообщений: 22
Пользователь №: 43234
На форуме:
Карма:Здравствуйте! Собственно, мой вопрос заключён в названии темы.
Как вывести имя пользователя на страницу? Тестирую в Денвере.
Пробую вставить этот код:Профиль
Группа: ★ЛжеЭксперт★Сообщений: 2642
Пользователь №: 37963
На форуме:
Карма: 29Сообщений: 1122
Пользователь №: 37872
На форуме:
Карма: 43Профиль
Группа: Пользователь
Сообщений: 22
Пользователь №: 43234
На форуме:
Карма:Я только начинаю учить PHP+MySQL. В качестве наглядного пособия для себя скачал готовый архив с файлами для регистрации и авторизации. Всё прекрасно работает.
Вот код php-файла, в который я хочу добавить код вывода имени пользователя на страницу, но почему-то не получается.
/**
* Скрипт распределения ресурсов
* Проверяем права на чтение данных,
* только для зарегистрированных пользователей
*/
//Проверяем зашел ли пользователь
if($user === false)
echo 'Доступ закрыт, Вы не вошли в систему!
'."\n";
>
if($user === true)
echo 'Поздравляю, Вы вошли в систему!
'."\n";
echo '.BEZ_HOST.'?mode=auth&exit=true"> ';
//Вот сюда я хочу вставить код вывода имени пользователя на страницу
echo $_SESSION["email"];
>
?>Это сообщение отредактировал Comer — 7.08.2016 — 20:22
Профиль
Группа: ★ЛжеЭксперт★Сообщений: 2642
Пользователь №: 37963
На форуме:
Карма: 29Профиль
Группа: Пользователь
Сообщений: 22
Пользователь №: 43234
На форуме:
Карма:Профиль
Группа: ★ЛжеЭксперт★Сообщений: 2642
Пользователь №: 37963
На форуме:
Карма: 29Профиль
Группа: Пользователь
Сообщений: 22
Пользователь №: 43234
На форуме:
Карма://Я хочу вставить этот код
echo $_SESSION["email"];Профиль
Группа: ★ЛжеЭксперт★Сообщений: 2642
Пользователь №: 37963
На форуме:
Карма: 29Профиль
Группа: Пользователь
Сообщений: 22
Пользователь №: 43234
На форуме:
Карма:Цитата (Медведь @ 7.08.2016 — 20:22) 😆 всё.. я под стулом ))
/**
* Обработчик формы авторизации
* Авторизация пользователя
*/
//Выход из авторизации
if(isset($_GET['exit']) == true)
//Уничтожаем сессию
session_destroy();
//Делаем редирект
header('Location:'. BEZ_HOST .'?mode=auth');
exit;
>
//Если нажата кнопка то обрабатываем данные
if(isset($_POST['submit']))
//Проверяем на пустоту
if(empty($_POST['email']))
$err[] = 'Не введен Логин';
if(empty($_POST['pass']))
$err[] = 'Не введен Пароль';
//Проверяем email
if(emailValid($_POST['email']) === false)
$err[] = 'Не корректный E-mail';
//Проверяем наличие ошибок и выводим пользователю
if(count($err) > 0)
echo showErrorMessage($err);
else
/*Создаем запрос на выборку из базы
данных для проверки подлиности пользователя*/
$sql = 'SELECT *
FROM `'. BEZ_DBPREFIX .'reg`
WHERE `login` = :email
AND `status` = 1';
//Подготавливаем PDO выражение для SQL запроса
$stmt = $db->prepare($sql);
$stmt->bindValue(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->execute();
//Получаем данные SQL запроса
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Если логин совподает, проверяем пароль
if(count($rows) > 0)
//Получаем данные из таблицы
if(md5(md5($_POST['pass']).$rows[0]['salt']) == $rows[0]['pass'])
$_SESSION['user'] = true;
//Сбрасываем параметры
header('Location:'. BEZ_HOST .'?mode=auth');
exit;
>
else
echo showErrorMessage('Неверный пароль!');
>else
echo showErrorMessage('Логин '. $_POST['email'] .' не найден!');
>
>
>
?>Это сообщение отредактировал Comer — 7.08.2016 — 20:32