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
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.
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!
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.
Execute whoami
:
<?php echo exec('whoami'); ?>
Use this:
$_SERVER['REMOTE_USER'];
this variable may or may not be set.