How to execute shell commands via PHP

This post discusses how to execute shell commands via PHP. Thus, rather than manually entering a command in Linux to search the folder structure, you do this programmatically via PHP. The ability to execute shell commands via PHP is a powerful feature and should be used carefully. Not all hosting providers will allow you to execute shell commands via PHP.

The PHP function to execute shell command is: shell_exec(), Β exec() or system().

These functions are very similar, but have slight differences:

  • shell_exec() returns the complete output as a string. The string can be NULL when an error occurs or if the command produces no output.
  • exec() returns the last line of the executed command as a string. NOTE: Use exec() when you require access to the program exit.Β  shell_exec() does not provide the program exit code information.
  • system() is similar to shell_exec() but displays output directly (without using echo() or print()).

shell_exec() & exec() example:

Both of these shell functions work the same way. Note the previously mentioned differences.

<?
echo shell_exec("ls / -ltr");
?>

Result:

total 2097248 drwxr-xr-x 2 root root 4096 Apr 26 19:07 opt drwxr-xr-x 2 root root 4096 Apr 26 19:07 media drwxr-xr-x 2 root root 4096 Apr 26 19:07 lib64 lrwxrwxrwx 1 root root ….

The response contains \n line breaks. Use str_replace(“\n”, “<BR>”, shell_exec(“ls / -ltr”)) to replace newline characters with HTML friendly BRs.

Example:

total 2097248
drwxr-xr-x 2 root root 4096 Apr 26 19:07 opt
drwxr-xr-x 2 root root 4096 Apr 26 19:07 media
drwxr-xr-x 2 root root 4096 Apr 26 19:07 lib64

system() example:

The system() function is also usedΒ to execute shell commands via PHP.

<?
system("ls / -ltr");
?>

Result:

total 2097248 drwxr-xr-x 2 root root 4096 Apr 26 19:07 opt drwxr-xr-x 2 root root 4096 Apr 26 19:07 media drwxr-xr-x 2 root root 4096 Apr 26 19:07 lib64 lrwxrwxrwx 1 root root ….

Visit https://anto.online for more posts about PHP!



About the Authors

Each member of Anto's editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic!

Support the Cause

Support Anto Online and buy us a coffee. Anything is possible with coffee and code.

Buy me a coffee



2 Comments on “How to execute shell commands via PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *