Better PHP exec() & Things to remember

/**
 * Run command, get output and exit code.
 */
function run_command($command) {
    $output = [];
    exec($command, $output, $exitcode);

    // Trim, Remove empty strings, then Reset keys.
    $output = array_values(array_filter(array_map('trim', $output), function($string) {
        return $string !== '';
    }));

    return [$output, $exitcode];
}

If a binary located in /usr/local/bin then PHP won’t find the binary if you run the script via Cronjob. That’s because in Crontab, the default shell is /bin/sh and $PATH is /usr/bin:/bin Also, PHP internally calls /bin/sh (not /bin/bash). The script may work normally, but won’t work in Cronjobs. So, always put binaries in /usr/bin or make symlink.

Tags