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

前端 未结 5 1026
生来不讨喜
生来不讨喜 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.

提交回复
热议问题