Вывести имя пользователя php

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

    Источник

    Как вывести имя авторизованного пользователя?

    Exploding

    Только Вы бы почитали про sql-инъекции, а то так пихать в запрос все что не попадя — все равно что тянуть все в рот, что на дороге нашел.

    BadassRolf

    BadassRolf

    на счет $user[‘name’]; не понятно. у меня он нигде не хранится, я вам скинул весь код.
    как его записать можно?

    Exploding

    BadassRolf: вместо name — любое имя поля которое хотите чтобы выводилось в качестве имени, наверно тогда $user[«login»], если более подходящего нет ничего:)

    BadassRolf

    Exploding

    BadassRolf

    Exploding

    774462ce6a3c41f494eaca20d7c1352e.jpg

    Ну так правильно! Причем тут кнопка. Поле называется login!
    измените на это:
    if (isset($_POST[‘login’]))

    Exploding

    BadassRolf

    Exploding: на странице с формой находится экшн. при вводе логина и пароля проверяется событие на нажие кнопки у которой имя login_u. после этого идет сверение и устанавливается сессия.
    если поставить как вы сказали, тогда не работает

    Exploding

    BadassRolf

    Exploding

    BadassRolf: И хотя бы привести пример ошибки, которую выдает интерпретатор, а не просто «не работает».
    Контроль ошибок включается: error_reporting(-1);

    BadassRolf

    Exploding

    Уффф. вот так 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"];

    BadassRolf

    Exploding

    Exploding

    BadassRolf

    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']; >

    Exploding

    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 «Не правильно»;
    >
    >

    BadassRolf

    Exploding: я от силы php изучаю неделю. практикуюсь второй день) вот все и криво и как попало. с повышением знаний буду исправлять код)

    Exploding

    Но я бы разобрался! Т.к. фактически вы вроде бы и сверились с БД но как-то хреново сверились))) Почему логин не из записи БД берется а из поста?)))) Фен-шуй за это покарает колючей плетью))

    Exploding

    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

      Источник

      Читайте также:  Тип данных массив питон
Оцените статью