简体   繁体   中英

Get system user name through PHP or Javascript

How can I get current logged system username through PHP or JavaScript.

We have an built in function in Java such as:

String userName = System.getProperty("user.name");

but I could not find similar command in any of the technology I need.

I need it for web application, I am using following technologies/libraries for web application HTML, CSS, Bootstrap, Ajax, Jquery, Datatables, PHP, MS SQL.

Is there a way to find system user name through any of the mentioned technology.

The following will give you the user who is running the PHP process. For example, if you are running Apache, it will give you the user who owns the Apache process. If you run from the command line then you will get the user name of the logged in person.

If you run this through Apache (or any webserver) and that web server is running as user _www on your computer and you are logged in as user zippy , then these will return you _www , not zippy .

On linux or macOS:

$processUser = exec('whoami');

Or:

$userInfo = posix_getpwuid(posix_geteuid());
$processUser = $userInfo['name'];

You could also try to see if it is available through the environment.

$user = $_ENV['USERNAME'] ?? '-unknown';

I used the following Java as an example:

public class Main {
    public static void main(String[] args) {
        String username = System.getProperty("user.name");
        System.out.println("username = " + username);
    }
}

Then I used the following PHP:

<?php
echo `whoami`;
echo "\n";

Then I ran on the command line and got the exact same output.

On macOS and Linux, this will give you a list of all users currently logged in:

<?php
$users = exec('/usr/bin/users', $output);
print_r($output);

According to this Oracle Java doc System.getProperty("user.name") gives you "User account name". I am assuming that in a web server environment, this will give you the name of the user that is running the Java or Webserver process.

I am not entirely sure these work on Windows if that's what you are using.

<?php echo get_current_user(); ?>
<?php echo getenv("username"); ?>

See phpinfo() for more informations. Works on both Linux and Windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM