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

问题描述 投票:34回答:5

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

目录结构如下所示:

execute.php
Scripts/
    script.sh
php
5个回答
57
投票

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


24
投票

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

chdir()之前,只需使用exec()更改工作目录。


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
}

7
投票

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

exec('cd /path/to/scripts; ./script.sh');

除此以外,

exec('/path/to/scripts/script.sh'); 

应该足够了。


4
投票

这不是最好的方法:

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

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

改为:

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

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

这是一个使用shell优化表达式求值方式的技巧:因为这是一个AND运算,如果左边的部分没有计算为TRUE,那么整个表达式就不能评估为TRUE,所以shell不会进行事件处理正确的表达部分。

© www.soinside.com 2019 - 2024. All rights reserved.