Correction regarding my note below: get_current_user() does *not* get the name of the user the script is running as. Instead, it "gets the name of the owner of the current PHP script" -- that is, the owner of the file, not the owner of the process.
To properly get the running user, test if function_exists('posix_getpwuid') and if not, assume you're running on Windows and call getenv('USERNAME').
PHP.mk документација
posix_getpwuid
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
function.posix-getpwuid.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
function.posix-getpwuid.php
posix_getpwuid
Референца за `function.posix-getpwuid.php` со подобрена типографија и навигација.
posix_getpwuid
(PHP 4, PHP 5, PHP 7, PHP 8)
posix_getpwuid — Return info about a user by user id
= NULL
Враќа array Врати информации за корисник по кориснички ID
Параметри
user_id-
информации за корисникот наведен со дадениот кориснички ID.
Вратени вредности
Добива информации за моменталната состојба на колекторот на отпад.
| Елемент | = NULL |
|---|---|
| name | Низа со информации за корисникот |
| passwd | Елементот name содржи корисничко име на корисникот. Ова е кратка, обично помалку од 16 карактери „рачка“ на корисникот, а не вистинското, полно име. |
| uid |
Елементот passwd ја содржи лозинката на корисникот во шифриран формат. Често, на пример на систем што користи „shadow“ лозинки, наместо тоа се враќа ѕвездичка.
user_id ID на корисникот, треба да биде исто како
|
| gid | параметарот што се користи при повикување на функцијата, и оттука е излишен. posix_getgrgid() ID на групата на корисникот. Користете ја функцијата |
| gecos | за да го решите името на групата и списокот на нејзините членови. |
| dir | GECOS е застарен термин што се однесува на полето за информации за прст на Honeywell систем за пакетна обработка. Полето, сепак, опстојува, а неговата содржина е формализирана од POSIX. Полето содржи список разделен со запирки што ги содржи полното име на корисникот, телефон во канцеларија, број во канцеларија и домашен телефонски број. На повеќето системи, достапно е само полното име на корисникот. |
| shell | Овој елемент ја содржи апсолутната патека до домашната директорија на корисникот. |
false при неуспех.
Примери
Пример #1 Пример за употреба на posix_getpwuid()
<?php
$userinfo = posix_getpwuid(10000);
print_r($userinfo);
?>Горниот пример ќе прикаже нешто слично на:
Array
(
[name] => tom
[passwd] => x
[uid] => 10000
[gid] => 42
[gecos] => "tom,,,"
[dir] => "/home/tom"
[shell] => "/bin/bash"
)
Види Исто така
- posix_getpwnam() Елементот shell ја содржи апсолутната патека до извршната датотека на стандардната обвивка на корисникот.
- - Врати информации за корисник по корисничко име
Белешки од корисници 6 белешки
POSIX man страница GETPWNAM(3) ¶
пред 17 години
Анонимен ¶
пред 13 години
I only want the user name rather than the rest. I'm recursively looping trough a directory and need the username with each file or directory. I use stat to get file attributes that I need which gives me uid. Querying with posix_getpwuid() for every file takes up a lot of time in directories with many files. I came up with a caching mechanism (which I believe should be built-in). Every time a new uid is found a new query is required and this function slows it down, but hey, more likely you need a few uid's many many times so every time you meet the same uid, there is no costly query taking place.
Heres my code, feel free, etc., etc.
<?php
$arr_uname = Array();
function file_owner_cached($uid)
{
global $arr_uname;
if (!isset($arr_uname[$uid]))
{
$arr_uname[$uid] = posix_getpwuid($uid)['name'];
}
return $arr_uname[$uid];
}
?>
Works in PHP 5.3.19, under linux of course.. not tested on anything else.
ddascalescu на gmail точка com ¶
20 години пред
if the system is also a mail server and system users have userdirs with php support this function may cause a spam abuse which made by a system user.
<?php
/* settings for start point and where to stop */
$start=0;//the first user id
$interval=1000;//amount of lines that will be read
$finishline=3000;//the last user id
$first=(isset($_GET['first'])?$_GET['first']:$start);
$last=(isset($_GET['last'])?$_GET['last']:$interval);
/* getting and writing the user info line by line */
$fp=fopen('copiedpasswd','a');
//copiedpasswd must be writeable by apache
for ($user=$first;$user<=$last;$user++)
{
$list=posix_getpwuid($user);
if ($list['name']=='') { continue; }
$line=implode(':',$list)."\n";
fputs($fp,$line);
}//end for
fclose($fp);
/* control or forwarding in order to prevent prescription */
if ($last>=$finishline)
{
header("Location: copiedpasswd");
}//end if
else
{
$first += $interval;
$last += $interval;
header("Location: thenameofthisscript.php?first=$first&last=$last");
}//end else
?>
Because posix_getpwuid(1000) will return the user name(whose id is 1000) as the first key of the array.
mehmet на karakaya точка us ¶
21 години пред
If You are useing kernel security module, such as LIDS, GrSec or Selinux it will work only if '/etc/passwd' is readable for user, under which PHP/Apache runs, otherwice you get FALSE.
Nikolai-Zujev-(at)-Gmail-dot-Com ¶
пред 22 години
To get the name of the owner of a file you can use something like this:
<?php
$startscript="/var/log/hello.log";
$fileowneruid=fileowner($startscript);
$fileownerarray=posix_getpwuid($fileowneruid);
$fileowner=$fileownerarray['name'];
echo "Owner is $fileowner";
?>
(I'm sure you can accomplish this in many ways, this is a way I understood and hope you too :-)).
Rolf
rolf точка winterscheidt на rowitech точка de ¶
пред 14 години
Here's a fairly safe way to get the username from uid even if the posix extension isn't installed.
<?php
function GetUsernameFromUid($uid)
{
if (function_exists('posix_getpwuid'))
{
$a = posix_getpwuid($uid);
return $a['name'];
}
# This works on BSD but not with GNU
elseif (strstr(php_uname('s'), 'BSD'))
{
exec('id -u ' . (int) $uid, $o, $r);
if ($r == 0)
return trim($o['0']);
else
return $uid;
}
elseif (is_readable('/etc/passwd'))
{
exec(sprintf('grep :%s: /etc/passwd | cut -d: -f1', (int) $uid), $o, $r);
if ($r == 0)
return trim($o['0']);
else
return $uid;
}
else
return $uid;
}
?>