Executing Linux Commands With PHP on Debian Based Systems


Using Ubuntu and Debian To Run Shell Commands With PHP Scripts

Linux has many great packages that you can install use with some command line knowledge. However, there may come a time when you run to use a package and execute the commands from a web browser.

Typically, PHP functions like exec() and shell_exec() can be used to run basic commands that can navigate folders and read files.

But, what if you want to use a package and run a command within the browser? To do this, you will need to allow www-data to become sudoer user and allow it to use the package without a password. This article will explain how to do that.

By default, Apache will run with the user www-data. So, open up that /etc/sudoers file and give Apache permission to use the desired service(s). For this example, we will use the service httrack.

 www-data ALL=NOPASSWD: /usr/bin/httrack 

Now, we can run the exec() and shell_exec() functions to use httrack.The sample code would copy the files in root folder and skip the rest of the stuff since it only goes 1 folder deep.

 <?php shell_exec('sudo httrack "http://example.com/" -O "/websites/example.com" -v -s0  --depth=1');