【发布时间】:2009-11-05 08:08:59
【问题描述】:
我的脚本,我们称之为execute.php,需要启动一个位于Scripts 子文件夹中的shell 脚本。必须执行脚本,使其工作目录为 Scripts。如何在 PHP 中完成这个简单的任务?
目录结构如下:
execute.php
Scripts/
script.sh
【问题讨论】:
标签: php
我的脚本,我们称之为execute.php,需要启动一个位于Scripts 子文件夹中的shell 脚本。必须执行脚本,使其工作目录为 Scripts。如何在 PHP 中完成这个简单的任务?
目录结构如下:
execute.php
Scripts/
script.sh
【问题讨论】:
标签: php
您可以在 exec 命令 (exec("cd Scripts && ./script.sh")) 中更改到该目录,或者使用 chdir() 更改 PHP 进程的工作目录。
【讨论】:
/Users/[user]/Scripts/。我很惊讶 $_SERVER 数组中的值都不是“此文件父位置的路径”。这样做的唯一方法是获取脚本的完整路径并将其分解为一个数组,然后在没有最后一部分的情况下重建它?
__DIR__
当前工作目录与 PHP 脚本的当前工作目录相同。
只需在exec() 之前使用chdir() 更改工作目录。
【讨论】:
这不是最好的方法:
exec('cd /patto/scripts; ./script.sh');
将此传递给 exec 函数将始终执行 ./scripts.sh,如果 cd 命令失败,这可能会导致脚本无法在正确的工作目录中执行。
改为这样做:
exec('cd /patto/scripts && ./script.sh');
&& 是 AND 逻辑运算符。使用此操作符,只有在cd 命令成功时才会执行脚本。
这是一个使用 shell 优化表达式求值方式的技巧:因为这是一个 AND 操作,如果左侧部分不求值为 TRUE,则整个表达式无法求值为 TRUE,因此 shell 获胜t 事件处理表达式的右侧部分。
【讨论】:
为了更好地控制子进程的执行方式,您可以使用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
}
【讨论】:
如果你真的需要你的工作目录是脚本,试试:
exec('cd /path/to/scripts; ./script.sh');
否则,
exec('/path/to/scripts/script.sh');
应该足够了。
【讨论】: