How do I find out, which user is running the current php script?

前端 未结 5 1002
生来不讨喜
生来不讨喜 2021-01-11 14:21

How do we determine which user the php script is running under when I run the script on server? Is it running under the same user as apache or phpmyadmin by chance? My quest

相关标签:
5条回答
  • 2021-01-11 14:48

    If you have posix functions available (enabled by default in most Linux-based environments) then you can use posix_geteuid and posix_getpwuid to get the name of the user (at least in non-Windows environments) like so:

    $pwu_data = posix_getpwuid(posix_geteuid());
    $username = $pwu_data['name'];
    

    Another (more expensive) way to do it would be to use a shell-executing function like exec to run whoami:

    $username = exec('whoami');
    

    or even the backticks (although you may need to trim the linebreak off):

    $username = `whoami`;
    

    I personally have only ever needed to get the username of the user running the script for PHP scripts that run in the shell (on the command-line). Typically, scripts that run in the process of building the response to a request that the web server is handling will be run as the web server user, such as www-data, apache, etc. In Apache, the user that runs the apache/httpd processes is set with the User directive.

    Important note: get_current_user does NOT give you the username of the user running the script, but instead gives you the OWNER of the script. Some of the answers here (appropriately down-voted) are suggesting to use get_current_user, but that will not give you the username of the user running the current script.

    0 讨论(0)
  • 2021-01-11 14:50

    Do not use "whoami". When you execute a process the user will not necessarily be the same as the effective user during running of a script. But in any case "id" would provide much more useful information. Instead call get_current_user(). So simple!

    0 讨论(0)
  • 2021-01-11 14:56

    Use this:

    echo get_current_user();
    

    Make sure to read the comments because it looks like this answer doesn't actually do what you want.

    0 讨论(0)
  • 2021-01-11 14:59

    Execute whoami:

    <?php echo exec('whoami'); ?>
    
    0 讨论(0)
  • 2021-01-11 15:05

    Use this:

    $_SERVER['REMOTE_USER'];
    

    this variable may or may not be set.

    0 讨论(0)
提交回复
热议问题