PHP sudo in shell_exec

Show Details

Solution 1: [1]

The problem isn't that your page is or isn't secure, the problem is that giving a php page the ability to run some sudo command would give it to all pages including any injected code on any insecure page on any site on the server.

That said, it might be best to make a wrapper script that does just the one job that needs doing, then give the http user access to just that ONE command as sudo

http  ALL=(ALL) NOPASSWD:/user/local/bin/

Solution 2: [2]

Definitley not advised. However, you will want to look into editing the sudoers file and add the user php is running as a NOPASSWD for the command you need to run. This will only allow him to sudo that one command with out entering a password.

If you need more commands add more to it. Sudoers Configuration I know that forum/post is debian based but sudo is not strictly debian and that should help you out with the sudo configuration values that you need to put it.

Solution 3: [3]

I just Google'd for php sudo shell_exec and this came up as the #1 match:

ilya at linemedia dot ru 16-Dec-2010 04:36
sudo can be executed without storing pass in a file

system('echo "PASS" | sudo -u root -S COMMAND');

Solution 4: [4]

$aux=echo "admin-pass" | your command;
echo $aux;

/******************************* ************Example************* *******************************/

Run a Perl script named

$aux=echo "admin-pass" | sudo -u root -S perl /path-to-the-script/;
echo $aux;

Solution 5: [5]

Best way to do it:

$descriptorSpec = array(
    0 => STDIN,
    1 => STDOUT,
    2 => STDERR,

if (posix_getuid() === 0) {
    echo "Root\n";
} else {
    echo "No root\n";
    $command = 'sudo ' . PHP_BINARY . ' ' . implode(' ', $_SERVER['argv']);

    $pipes = [];
    $process = proc_open($command, $descriptorSpec, $pipes);
    if (is_resource($process)) {

It runs the same command again, with sudo prefixed.


This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Credit
Solution 1 Caleb
Solution 2 Jim
Solution 3 drudge
Solution 4 SamyOteroGlez
Solution 5 Timon de Groot