How to execute linux command using PHP

Linux has some very useful commands that every developer need sometime to use save his time and effort. Like downloading a huge from another server, finding some text in all files etc. Most of the Popular GUI hosting control panels e.g. cPanel, Plesk, vDesk etc doesn’t provide such actions to perform. Sometimes its difficult to get SSH access of a server. In such case we can use php shell execute command to execute linux commands.
In this tutorial I am going to tell how to execute linux commands using PHP using a customized php command prompt as available to download in this tutorial.

Syntax of php shell_exec function is:

string shell_exec ( string $cmd )

$cmd is a command to execute. shell_exec function return the result of command execution. If there is some error in execution of command or there is not output the function will return NULL. We can’t detect the cause of execution failures using this function.

Note:- All linux commands are not possible to execute using shell_exec. Also this function will not work if it is added in the list of disabled function in php.ini file. So if this command is not working on your server then better check the list of disabled commands in php.ini file.

Let me explain me the usage of this function with some examples:

Example #1:

$result=shell_exec("ls -al");
echo "<pre>".$result."</pre>";

The above example will list all files and directory in current directory along with their size, date modified and permissions.

Example #2:

$result=shell_exec("zip -r zipfile.zip .");
echo $result;

The above example will create a zip archive file that contains all files and directory(including its subdirectories and files) and store it in the same directory.

I developed a simple “Linux Command Prompt” to execute linux commands on server. You can download the “Linux Command Prompt” from below download link.
Following are the steps to install command prompt on server.

  1. Download and extract the file.
  2. Uploaded the extracted “command” directory on your server where you can access it using url.
  3. Open the following URL in address bar of your browser: yourdomain.com/path-to-directory/command


About the author

Sujeet Kr Singh