user2880391
user2880391

Reputation: 2791

Linux - create user through PHP

I'm writing a PHP program that calls bash scripts. I'm using Linux (Centos). I'm trying to create a new user in Linux by entering username and password in the PHP page. this is the script I'm using:

egrep "^$1" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
    echo "$1 exists!"
    exit 1
else

    sudo useradd -m -p $2 $1
    [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi

this is how I call the script from PHP:

echo exec("/var/www/html/addUser.sh ".$username." ".$password);

it works when running it from terminal, but when calling the script from PHP it doesn't work. it is a matter of permissions. what should I do in order to allow the PHP (apache) to also add users? I've tried adding 'apache' to visudo both as user and as a group:

%apache ALL=(ALL)   NOPASSWD: ALL
 apache    ALL=(ALL)       ALL

it still doesn't work. any ideas? thanks.

Upvotes: 0

Views: 2219

Answers (1)

SteJ
SteJ

Reputation: 1541

You are attempting to let PHP run arbitary code on a web server as root -- this is extremely inadvisable, as if someone were to find a hole in your code and inject their own, they would literally be able to do anything they liked with your server!

That being said, you can call an external script using exec("command"); or use backticks like:

$command_output = `shell_command`;

For more information see php's exec function

If you really do want to proceed with this, I would suggest storing your script (the one at the top that you'd like to run) and then calling that script with exec(), while only allowing sudo passwordless access to that one script.

Additional:

You might want to try shell_exec instead of exec - this runs your command in a shell, which I think might fix any environment issues you may be having.

Upvotes: 2

Related Questions