Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to detect if user is root/sudo? [duplicate]

Tags:

linux

php

sudo

root

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!

like image 776
DOOManiac Avatar asked Jan 02 '14 17:01

DOOManiac


2 Answers

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.

like image 164
Andy Avatar answered Oct 21 '22 20:10

Andy


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

like image 29
Ed Heal Avatar answered Oct 21 '22 20:10

Ed Heal