PHP exec()命令:如何指定工作目录?

tpu*_*nen 34 php

我的脚本,我们称之为execute.php,需要在Scripts子文件夹中启动一个shell脚本.脚本必须执行,因此它的工作目录是Scripts.如何在PHP中完成这个简单的任务?

目录结构如下所示:

execute.php
Scripts/
    script.sh
Run Code Online (Sandbox Code Playgroud)

sou*_*rge 58

您可以在exec命令(exec("cd Scripts && ./script.sh"))中更改到该目录,也可以使用更改PHP进程的工作目录chdir().

  • @l008com 使用可以使用[`__DIR__`](https://www.php.net/manual/en/language.constants.predefined.php#constant.dir) (2认同)

mau*_*ris 26

当前工作目录与PHP脚本的当前工作目录相同.

只需chdir()用来更改工作目录exec().


Ins*_*lah 8

为了更好地控制子进程的执行方式,可以使用proc_open()函数:

$cmd  = 'Scripts/script.sh';
$cwd  = 'Scripts';

$spec = array(
    // can something more portable be passed here instead of /dev/null?
    0 => array('file', '/dev/null', 'r'),
    1 => array('file', '/dev/null', 'w'),
    2 => array('file', '/dev/null', 'w'),
);

$ph = proc_open($cmd, $spec, $pipes, $cwd);
if ($ph === FALSE) {
    // open error
}

// If we are not passing /dev/null like above, we should close
// our ends of any pipes to signal that we're done. Otherwise
// the call to proc_close below may block indefinitely.
foreach ($pipes as $pipe) {
    @fclose($pipe);
}

// will wait for the process to terminate
$exit_code = proc_close($ph);
if ($exit_code !== 0) {
    // child error
}
Run Code Online (Sandbox Code Playgroud)


tim*_*dev 7

如果您确实需要将您的工作目录作为脚本,请尝试:

exec('cd /path/to/scripts; ./script.sh');
Run Code Online (Sandbox Code Playgroud)

除此以外,

exec('/path/to/scripts/script.sh'); 
Run Code Online (Sandbox Code Playgroud)

应该足够了.


小智 7

这不是最好的方法:

exec('cd /patto/scripts; ./script.sh');

将此传递给 exec 函数将始终执行 ./scripts.sh,如果cd命令失败,这可能会导致脚本无法使用正确的工作目录执行。

这样做:

exec('cd /patto/scripts && ./script.sh');

&&是 AND 逻辑运算符。使用此操作符,只有在cd命令成功时才会执行脚本。

这是一个使用 shell 优化表达式计算方式的技巧:由于这是一个 AND 运算,如果左侧部分的计算结果不为 TRUE,那么整个表达式无法计算为 TRUE,因此 shell 不会进行事件处理表达式的正确部分。

  • 我无法理解这个答案在说什么。哪种方式“不是最好的方式”?你是说你推荐使用 && 还是 ; (分号)?您给出的解决方案使用分号,但在下一句中,您似乎在说最好使用&&。 (6认同)