In case you have been digging the web for a solution on how to execute root commands through a PHP script, here's a quick note on it. First, you have to know that executing root commands through a PHP script is very risky. But, for the purpose of giving quick solution to this problem, I will share one way to do it.
Here are the steps:
1. Determine what user your php script is running in your web server. Commonly, this will be 'apache'. But if you want to make it sure, create a test script and add the following code:
<?php
echo shell_exec('whoami');
?>
The output must the actual username that your script is using while it runs.
2. To execute root commands through your php script you have to make it sure that the username you get in the preceeding step is a sudo user. To do this you have to add this user in the sudoers file. Here's how to do it:
# sudoers file.
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the sudoers man page for the details on how to write a sudoers file.
#
# Host alias specification
# User alias specification
# Cmnd alias specification
# Defaults specification
# User privilege specification
root ALL=(ALL) ALL
theuser ALL=(ALL) allowable_root_commands NOPASSWD: ALL
# Uncomment to allow people in group wheel to run all commands
# %wheel ALL=(ALL) ALL
# Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL
# Samples
# %users ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
# %users localhost=/sbin/shutdown -h now
3. Run any command you have specified in the allowable_root_commands through the shell_exec() function. Example:
<?php
echo shell_exec('whoami');
echo shell_exec('sudo service xinetd restart');
?>
That's it! Remember that this is just quick solution. There are many other ways that are more secure such as creating a server where you can pass the commands you want to execute using sockets.
Again, this is not a recommended solution.


Comprehensive resources for web development and Internet in general.
3 comments:
Hello,
I hope I will found my question answer. Because I search many website's and still found nothing.
I need login or use root access via php, I just start make control panel. So Im using system and root shell commands.
How do i gain root access via using php and login as a root using php ?
I have Apache2 and php5 installed.
hi,
i have tried with my syntax. but before it,i did:
#visudo
//i write this under root
fibie ALL=(ALL) allowable_root_commands NOPASSWD: ALL
but,it showed
>>> sudoers file: syntax error, line 22 <<<
i thing my line above is wrong.can you help me?
Hi,
I've executed the whoami command from PHP script and get the user as 'www-data'.
Now I want to execute useradd command from the same script. I've edited the sudo configuration with visudo and added the line:
www-data ALL=(ALL) useradd NOPASSWD: ALL
But when the useradd is called from the php file by system it returns an error status 1. Am I doing anything wrong with the sudo config?
Post a Comment