php exec() function and different hosts

后端 未结 3 1943
时光说笑
时光说笑 2021-01-21 08:20

I have a script that executes a file in a couple of directories down which looks like this:

exec(\"php-cli $file_path > /dev/null 2>/dev/null &\"); //p         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 09:00

    function php_exec($file_path) {
        if (!($binary = which(array('php', 'php5', 'php-cli', 'php-cgi'))))
            return false;
    
        return exec("$binary $file_path > /dev/null 2>/dev/null &");
    }
    
    function which($binaries) {
        if (!($path = getenv('PATH')) && !($path = getenv('Path')))
            return false;
    
        $arr = preg_split('/[:;]/', $path);
    
        foreach ($arr as $p) {
            foreach ($binaries as $b) {
                if (file_exists("$p/$b"))
                    return "$p/$b";
            }
        }   
    
        return false;
    }
    
    var_dump(php_exec('test.php'));
    

    Explanation: On most systems the PHP binary is called php, php5, php-cli or php-cgi. which() function checks the standard path (both *nix and windows have environment variable called PATH/Path) for each of those names and if it find a file with such name, it will return it.

    The PATH variable's format is: /bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin for *nix (bash), and C:\Windows\System32\;C:\Windows\; for windows, so that's why I use preg_split('/[:;]/')

    This solution is better than yours, because php_exec() will return false if it can't find a valid php binary. In your solution there's no way to know if the script execution failed.

提交回复
热议问题