How to make a check to find whether the script is run with sudo access or not using PHP ?
Note: this question would probably be more appropriate on Stack Overflow, even though it refers to PHP on Unix & Linux systems (privilege elevation, permissions, etc.).
You can use PHP's POSIX functions:
Here is a little example:
<?php
$userinfo = posix_getpwuid(posix_geteuid());
echo "This script runs with " . $userinfo["name"] . "'s privileges.";
?>
Testing...
$ php myfile.php
This script is run with myuser's privileges.
$ sudo php myfile.php
This script is run with root's privileges.
By the way, since root is always UID 0, you could just check posix_geteuid() == 0
.
Now, if you want to now whether the user is using the CLI (command-line) or going through the web server, have a look at this question on Stack Overflow and the php_sapi_name()
function.
Another note: I'm pretty sure that running PHP scripts as root isn't the best of ideas. You may want to think again about what permissions your script really needs.
If it's purely about determining whether sudo
is used, sudo
puts a number of values in the environment of the command:
SUDO_COMMAND=/usr/bin/commandname
SUDO_USER=wurtel
SUDO_UID=1000
SUDO_GID=1001
These can be checked in php using the getenv()
function. Of course, combine it with posix_geteuid()
function to make sure you really do have elevated privileges as anyone can set those values in the environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With