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

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:

  • http://us1.php.net/empty
  • http://stackoverflow.com/questions/12424787/how-to-check-if-a-shell-command-exists-from-php

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

One 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.

Add your voice!