I have a command line PHP script that needs to be run with root-level permissions on Linux systems.
On our old, old Redhat Enterprise 2 Linux distro, this code worked:
// If we are linux, make sure we're root
if ($bIsLinux && $_ENV['USER'] != 'root')
die("This script must be run as root.\n");
However, we've upgraded servers and are now on a modern version of linux (Amazon Linux). Which is great, but the above no longer works. On AML, you don't actually have the root password, but you can sudo from ec2-user
. I've even tried sudo -i
but that doesn't change the environment variable - and thus the above code fails.
So I need a new way to ensure root-level privileges before continuing.
Anyone have any ideas?
Thanks!
Using posix_getuid you can check if a user is root.
<?php
if (posix_getuid() == 0){
echo "This is root !";
} else {
echo "This is non-root";
}
?>
0
is root, anything else is not.
Try http://uk3.php.net/posix_getuid and check if it returns zero. If so it is root. If not is is some other user
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