Php proc_open ‘su: must be run from a terminal’

PHPproc-openshellubuntu-12.04

I have this PHP code in a personal Ubuntu Server machine:


    $cmd = 'su testuser';
    $descriptorspec = array(
        array('pipe', 'r'),
        array('pipe', 'w'),
        array('pipe', 'w')
    );
    $pipes = array();
    $process = proc_open($cmd, $descriptorspec, $pipes);
    fwrite($pipes[0], 'password\r');
    fclose($pipes[0]);
    $string = array(stream_get_contents($pipes[1]), stream_get_contents($pipes[2]));
    proc_close($process);
    echo exec('whoami') . "\n";
    print_r($string);

And I get from PHP this response:

www-data
Array
(
    [0] =>
    [1] => su: must be run from a terminal

)

It's obvious I want to change the active user but is there any way to do this from php?

Best Answer

The su command will only change the current user while the bash shell it was executing in is still running. Even if you were to do $cmd = 'bash -c "sudo su testuser"' (which will execute as intended) you would only change the current user until you execute proc_close, so the exec('whoami') will always give you the username of the user who originally lauched your php script. But you can use the command in bold to execute a bash shell that will execute as testuser and then pipe commands to it. For instance if you pipe 'whoami' instead of 'nirvana3105\r' whoami should return 'testuser'. Hope that helps.

Try this code(replacing password with your password):

<?php
    $cmd = "sudo -S su testuser";

    echo $cmd;

    $desc = array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w'));
    $pipes = array();

    $process = proc_open($cmd, $desc, $pipes);
    fwrite($pipes[0], "password\n");
    fwrite($pipes[0], "whoami");
    fclose($pipes[0]);
    $string = array(stream_get_contents($pipes[1]), stream_get_contents($pipes[2]));
proc_close($process);

    print_r($string);
 ?>