How to test if a Shell Command can be executed in PHP

- by

Before we execute a shell command from PHP it’s a good idea to test if the server will respond to it. We can do this by making use of the empty() function.

The following example consists of a helper function you can call before executing the command in question. Then we call it with the shell command we intend to use, before executing the command for real. We’re using ‘uname -a’ here as an example that will generate output and takes a parameter:

// helper function
function checkShellCommand($command) {
    $returnValue = shell_exec("$command");
	if(empty($returnValue)) {
		return false;
	} else {
		return true;
	}
}

// test the shell command you'd like to use
if (!checkShellCommand('uname -a')) {
    print 'This command cannot be executed.';
} else {
    echo shell_exec('uname -a');
}


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

1 thought on “How to test if a Shell Command can be executed in PHP”

  1. function checkShellCommand($command) { return !empty(shell_exec(“$command”)); }
    It’s shorter and …I wonder myself if it’s really needed to have a function for that.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.