PHP Check If A Linux Command Is Valid

PHP Check If A Linux Command Is Valid

Sometimes, you might end up using the linux terminal via PHP, and it is good practise for you to perform checks before executing commands. Here’s how you can check if a command is even valid for that linux terminal, or OS.

In linux, the command would be command -v <command>. In this scenario, for example, command -v ifconfig. If the ifconfig command exists, then it would return the path of the associated command like so¬†/usr/sbin/ifconfig. If the command doesn’t exist, then it would simply not return anything.

Here’s a simple PHP wrapper function to perform the task mentioned above.

function is_command_valid($command)
{
    $check_command_string = "command -v {$command}"; // e.g command -v youtube-dl 
    exec($check_command_string, $output, $return_var);
    if( !empty($output) ) {
        return true;
    }
    return false;
}

To use it, simply call the function like so, is_command_valid('ifconfig');

That’s all.

Enjoyed the content ? Share it with your friends !