phpexecshell-exec

Changing directory in shell_exec does not work


I have this routine for running BASH-scripts:

// $cmd is something like '/var/tmp/script.sh'
function runshell($cmd)
{
    $work_dir = dirname($cmd);
    $work_file = basename($cmd);
    $message = shell_exec("cd " . $work_dir . " && " . $work_file . " 2>&1");
    return $message;
}

The problem is that it doesn't change directory and $work_file is never found


Solution

  • Solution1

    Use full path to file

    $message = shell_exec($work_dir . "/" . $work_file . " 2>&1");
    

    Solution2

    Also you can use chdir() for this. It will change current working directory of the PHP script.

    chdir($work_dir);
    $message = shell_exec($work_file . " 2>&1");