Radu Rădeanu
Radu Rădeanu

Reputation: 2722

Using exec() in PHP as an specific system user

When I use the following php script:

<?php
    echo 'I am '.exec('whoami').' user';
?>

on my localhost, the result is I am nobody user and is what I expect.

But when I use:

<?php
    echo 'I am '.exec('echo <PASSWD> | sudo -S -u <USER> whoami').' user';
?>

where <PASSWD> is my password and <USER> is my user name, the result is I am user and I expect to be I am <USER> user. How can I make it to work as I wish?


As a note, when I use echo 'I am '.exec('echo <PASSWD> | sudo -S -u <USER> whoami').' user'; inside php interpreter (php -a), everything is fine.

Upvotes: 2

Views: 3799

Answers (2)

Owen Beresford
Owen Beresford

Reputation: 722

A straight answer is you may need to go via shell to use the pipes etc

  • shell_exec..

For large scale applications, creating all those small processes is quite expensive.

IMO, a better solution is using these ::

  • pcntl_fork
  • posix_seteuid
  • posix_setegid
  • exec
  • Optional proc_nice

The calls to sudo are technically running with root permission. So this is the same, in a more visible fashion..

I'm sure you don't need me to tell you that putting those passwords in your source is a bad idea.

Upvotes: 0

Matthew R.
Matthew R.

Reputation: 4350

The user that is being used is the one running php/httpd process on the server. Depending on your server setup this could be Apache, root, or in FastCGI setups it can be any user or no user. This is a fallacy since there must always be a user. Typically shared hosting servers will try to circumvent allowing users to execute functions as a sudo user. This may be what you are experiencing.

Upvotes: 1

Related Questions